node 服务 excel导出

html前端调用
export function ExportExcel(data,fileName){

try {
    showLoading('下载中...');
    fetch('/down_excel', {
      method: 'POST',
      body: JSON.stringify({
        datas: dataSource,
        fileName:fileName,
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    })
    .then(response => response.blob())
    .then(blob => {
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a); 
      a.click();    
      a.remove();  
  
    }).catch(error => {
      console.log(error);
    })

  } catch (error) {
    console.log(error);
  }finally{
    hideLoading();
  }

}

node 服务调用
const XLSX = require('xlsx');
var stream = require('stream');

app.use(bodyParser.urlencoded({extended: false, limit:'100mb'}));
app.use(bodyParser.json({
limit:'100mb'
}));
app.post('/down_excel', (req, res) => {
console.log('server down_excel');
let datas2 = req.body.datas;
let fileName = req.body.fileName;
console.log('fileName',fileName);
function send_aoa_to_client(req, res, data, bookType) {

console.log('data',data.length);
var ws = XLSX.utils.json_to_sheet(data);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet");

/* generate buffer */
var buffer = XLSX.write(wb, {type:'buffer', bookType:bookType || "xlsx"});
res.set({
  'Content-Type': 'application/octet-stream',
  'Content-Disposition': `filename=22`,
  'Content-Length': buffer.length
});
var readStream = new stream.PassThrough();
readStream.end(buffer);
readStream.pipe(res);

}
send_aoa_to_client(req,res,datas2);
});

你可能感兴趣的:(node 服务 excel导出)