vue, koa import and export excel file

First, the use of node-xlsx, koa-multer plug npm install node-xlsx koa-multer mockjs --save
  

Two, excel file export

  1, the front end of the requested data, by blob (Blob container storage objects can be seen as binary data) parsing the data file corresponding to the download

 1 exportExcel(e){
 2    axios({
 3       method : "get",
 4       url : "/api/exportexcel",
 5       responseType: 'blob'
 6    }).then(async (res) => {
 7       let uploadExcel = (fileName) => {
 8             const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
 9             const url = URL.createObjectURL(blob);
10             const aLink = document.createElement('a');
11             aLink.setAttribute('download',fileName);
12             aLink.setAttribute('href',url);
13             document.body.appendChild(aLink)
14             aLink.click()
15             document.body.removeChild(aLink)
16             URL.revokeObjectURL(blob);
17       }
18       uploadExcel ( 'mySheetName.xlsx');
19   })
20}

 

   2, the rear end by the node-xlsx processing and returns the stream buffer data

. 1 const = NXlSX the require ( "Node-XLSX" );
 2 const = Mock the require ( "mockjs" );
 . 3 router.get ( '/ API / exportexcel', the async (CTX) => {
 . 4      // header 
. 5      const _headers = [ 'number', 'name', 'age', 'provincial', "city", "zone" ];
 6      // tabular data 
7      const _data = [... Mock.mock ({ 'arr | 30 -30 " : [{
 . 8          " ID | + 1'd ":. 1 ,
 . 9          name:" @cname " ,
 10          " Age | 18-34 ": 23 is ,
 . 11          " Province ":"@province",
12         "city" : "@city",
13         "county" : "@county"
14       }]}).arr];
15     let data = [];
16     for (let i =0 ; i < _data.length; i++){
17       let arr = [];
18       for(let key in _data[i]){
19         arr.push(_data[i][key])
20       }
21       data.push(arr);
22     }
23     data.unshift(_headers);  
24    // 数据格式为[["hello","223"],["22","23"]];
25     let= NXlSX.build buffer ([{name: "sheetName" , Data: Data}]);
 26 is      // return flow distal buffer 
27      ctx.body = buffer
 28 });

Three, excel file import, parse the returned rear distal end

  1, the front end by input [file] Files passed the rear end member

 1 importExcel(e){ 3     let file = e.currentTarget.files[0];
 4     let fileDir = file.name;
 5     let formData = new FormData();
 6     formData.append('file',file);
 7     let config = {
 8        headers: {
 9           'Content-Type': 'multipart/form-data'
10        }
11     }
12     axios.post("/api/importexcel",formData,config).then((res) => {
13          console.log(res);
14          // 处理数据
15
16     })
17 }   

  2, back-end storage file, process the data, and then delete the file

. 1 const = multer the require ( 'KOA-multer' );
 2 const = NXlSX the require ( "Node-XLSX" );
 . 3 the let = Storage multer.diskStorage ({
 . 4      // file path 
. 5      Where do you want: function (REQ, File, CB) {
 . 6        CB ( null , './server/data' )
 . 7      },
 . 8      // modify the file name 
. 9      filename: function (REQ, file, CB) {
 10        var fileFormat = (file.originalname) .split ( " . " );
 11        cb ( null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
12     }
13   })
14 //加载配置
15 let upload = multer({ storage: storage })
16 router.post('/api/importexcel',upload.single('file'),async (ctx) => {
17     let file =ctx.req.file.filename;
18     const xlsxfile = "./server/data/" + file;
19     async function readExcel() {
20       return new Promise((resolve,reject)=>{
21         let obj = NXlSX.parse(xlsxfile);
22         resolve(obj);
23       });
24     }
25     async function getData(v) {
26       ctx.body = v[0].data;
27       fs.unlinkSync(xlsxfile);
28     }
29     let dataObj =await readExcel();
30     await getData(dataObj);
31 });

 

 

 

Guess you like

Origin www.cnblogs.com/laixihongblog/p/11208756.html