Vue front-end imports excel to parse out Json, xlsx parses excel

Received a request today, import excel query

It doesn't seem to be difficult. The file is just transferred to the backend, but it needs to be paged. It is impossible to upload the {file, pageNum, pageSize} again when clicking the next page. Because the file cannot be cached (at least it is troublesome)
————Then we parse it out and pass the parameters directly to the backend————

xlsx.js

Introduce:

npm i xlsx 
import XLSL from 'xlsx'

html:

       <input type="file" @change="readWorkbookFromLocalFile"  >

js:

readexcel(e) {
    
    
   		//表格导入
       const files = e.target.files;
       const fileReader = new FileReader();
       fileReader.onload = ev => {
    
    
           try {
    
    
               const data = ev.target.result;
               const workbook = XLSX.read(data, {
    
    
                   type: "binary"
               });
               //取第一张表,不懂就看excel左下角
               const wsname = workbook.SheetNames[0]; 
               const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
               let toJson = ws// 转化成功的json
               
               //----------在这上面都可以直接复制----------

				//数据构造
               let excelJson=[]
               toJson.map(x=> {
    
    
                   excelJson.push(x['用户ID'])
               })
               this.$message.success("导入成功,正在查询")
               console.log(excelJson)
               
           } catch (e) {
    
    
               this.$message.error("导入失败")
               return false;
           }
       };
       fileReader.readAsBinaryString(files[0]);
   },

See the effect:

Each row of data corresponds to an array object. After
Insert picture description here
I construct the data
Insert picture description here

ps:

1. This html is a bit ugly, think of a way to optimize the style by yourself
2. This plug-in supports both .xls and .xlsx formats
3. Compatibility
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45629623/article/details/112894095