


How to implement Excel import and export functions on the front end (code example)
The content this article brings to you is about how the front-end implements Excel import and export functions (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In a recent project, I wanted to implement a function of importing and exporting Excel. After searching for some plug-ins, I found the js-xlsx plug-in, so I tried to use it. Here I will briefly record the usage method and the problems encountered.
SheetJS js-xlsx is a plug-in that can read and write tables in multiple formats. It has good browser support and can be used on multiple language platforms. It currently has 14k stars on github.
Plug-in address: https://github.com/SheetJS/js...
Use
1. Install dependencies
Enter Project folder, install xlsx
yarn add xlsx
2. Introduce
import * as XLSX from 'xlsx'
Export Excel function implementation into the project
1. Define what needs to be used when exporting Method
export default function download(json,fileName){ const type = 'xlsx'//定义导出文件的格式 var tmpDown;//导出的内容 var tmpdata = json[0]; json.unshift({}); var keyMap = []; //获取keys for (var k in tmpdata) { keyMap.push(k); json[0][k] = k; } var tmpdata = [];//用来保存转换好的json json.map((v, i) => keyMap.map((k, j) => Object.assign({}, { v: v[k], position: (j > 25 ? getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1) }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = { v: v.v }); var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10 var tmpWB = { SheetNames: ['mySheet'], //保存的表标题 Sheets: { 'mySheet': Object.assign({}, tmpdata, //内容 { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //设置填充区域 }) } }; tmpDown = new Blob([s2ab(XLSX.write(tmpWB, {bookType: (type == undefined ? 'xlsx':type),bookSST: false, type: 'binary'}//这里的数据是用来定义导出的格式类型 ))], { type: "" }); //创建二进制对象写入转换好的字节流 saveAs(tmpDown,fileName); } function saveAs(obj, fileName){//导出功能实现 var tmpa = document.createElement("a"); tmpa.download = fileName || "下载"; tmpa.href = URL.createObjectURL(obj); //绑定a标签 tmpa.click(); //模拟点击实现下载 setTimeout(function () { //延时释放 URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL }, 100); } function s2ab(s){ //字符串转字符流 var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } function getCharCol(n){ let temCol = '', s = '', m = 0 while (n > 0) { m = n % 26 + 1 s = String.fromCharCode(m + 64) + s n = (n - m) / 26 } return s }
2. Use the export method in the project
//导出excel //导出excel downloadExl = () => { const { results } = this.props //需要导出的json数据 let datas = _.clone(results)//这里为了不影响项目的数据的使用 采用了lodash中的深克隆方法 let json = datas.map(item=> { //将json数据的键名更换成导出时需要的键名 return { '人员ID' :item.id, '姓名' : item.name, '证件类型': this.findIdType(item.idType),//将类型代号转为汉字 '证件号码': item.credentialsId, '固定电话': item.tel, '移动电话': item.mobile } }) download(json,'人员信息.xlsx')//导出的文件名 }
3. Bind the event
<button>导出Excel</button>
This way you can easily Implemented the export function of Excel
Implementation of the import Excel function
1. Define the method to be used when importing
//导入excel onImportExcel = file => { // 获取上传的文件对象 const { files } = file.target; // 通过FileReader对象读取文件 const fileReader = new FileReader(); fileReader.onload = event => { try { const { result } = event.target; // 以二进制流方式读取得到整份excel表格对象 const workbook = XLSX.read(result, { type: 'binary' }); // 存储获取到的数据 let data = []; // 遍历每张工作表进行读取(这里默认只读取第一张表) for (const sheet in workbook.Sheets) { // esline-disable-next-line if (workbook.Sheets.hasOwnProperty(sheet)) { // 利用 sheet_to_json 方法将 excel 转成 json 数据 data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet])); // break; // 如果只取第一张表,就取消注释这行 } } // 最终获取到并且格式化后的 json 数据 const uploadData = data.map(item=> { return { id : Number(item['人员ID']), name : item['姓名'], idType: this.findIdType(item['证件类型'],'string'), credentialsId: item['证件号码'], tel: item['固定电话'], mobile: item['移动电话'] } }) console.log(uploadData)//这里得到了后端需要的json数据,调用接口传给后端就行了 message.success('上传成功!') //这里用了antd中的message组件 } catch (e) { // 这里可以抛出文件类型错误不正确的相关提示 message.error('文件类型不正确!'); } }; // 以二进制方式打开文件 fileReader.readAsBinaryString(files[0]); }
2. Bind events
<button> 导入Excel <input> //这里对原有的input样式进行了修改,accept 属性定义了上传文件支持的类型,onChange 操作中的 importExcel 方法定义了上传文件时执行的操作。 </button>
3. Modify the style
.upload_wrap { display: inline-block; position: relative; width: 94px; padding: 3px 5px; overflow: hidden; } .file_uploader { position: absolute; width: 100%; height: 100%; top: 0; left: 0; outline: none; opacity: 0; background-color: transparent; } .upload_text { display: inline-block; margin-left: 5px; } .upload_tip { display: inline-block; margin-left: 10px; color: #999; }
4. Make corresponding prompts for file upload and reading results (the message component in ant design is used here) )
5. Obtained json data
The import and export function is implemented in this way, is it very simple?
The above is the detailed content of How to implement Excel import and export functions on the front end (code example). For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.