nodejs使用export-excel插件將數據處理成excel表格返回,前端進行下載

標題 nodejs將數據處理成excel表格返回,前端進行下載。

node端代碼:請求數據的代碼省略了

var nodeExcel = require('excel-export');
var conf = {};
  conf.cols = [
    { caption: '配置', type: 'number' },
    { caption: '抓文方式', type: 'string' },
    { caption: '版面', type: 'string' },
    { caption: 'url', type: 'string' },
    { caption: 'pubcode', type: 'string' },
    { caption: '一級分類', type: 'string' },
    { caption: '二級分類', type: 'string' },
    { caption: '備註', type: 'string' },
    { caption: '狀態', type: 'number' },
    { caption: 'QC狀態', type: 'number' },
    { caption: '更新時間', type: 'string' },
  ];
  let data = [];
  let tou = [
    'config_status',
    'crawler',
    'section',
    'url',
    'pub_code',
    'category_1',
    'category_2',
    'remark',
    'status',
    'qc_status',
    'last_update_time',
  ];
  const [returnVal] = await Promise.all([connectPool.execute(queryListing)]);
    // if (returnVal[0].length === 0) {
    //   res.json({
    //     returnCode: ERROR_MYSQL_RESULT_ERROR,
    //     data: returnVal[0],
    //   });
    // }
    if (returnVal[0].length > 0) {//將請求來的數據轉換成export-excel要求的格式  (二維數組)
      for (let i = 0; i < returnVal[0].length; i++) {
        let arr = [];
        for (let j = 0; j < tou.length; j++) {
          arr.push(returnVal[0][i][tou[j]]);
        }
        data.push(arr);
      }
      conf.rows = data;
      console.log(conf);
      var result = nodeExcel.execute(conf);
      // var fs = require('fs');
			// fs.writeFileSync('d.xlsx', result, 'binary');
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition','attachment; filename=' + encodeURIComponent('report.xlsx'),);
    //   res.end(result, 'binary');
      res.json({
        returnCode: API_SUCCESS,
        data: result,
      });

前端代碼:

const downloadFileToExcel = ()=>{
    param.pageSize = 10000;
    clickListingDown(param);
    
  }
  useEffect(() => {
    if(listingDown!==""){
      const buf = Buffer.from(listingDown, 'binary')//將數據轉換成二進制流
      const blob = new Blob([buf], { type: 'application/vnd.ms-excel;charset=utf-8' });//將二進制數據存入blob對象
      let link = document.createElement('a');//添加a標籤
      let href = window.URL.createObjectURL(blob)//設置url
      link.href = href;//將url添加href屬性
      link.download = 'excel.xlsx';//設置文件名字
      document.body.appendChild(link);//添加dom節點
      link.click();//執行點擊操作
      document.body.removeChild(link); // 下載完成移除元素
      window.URL.revokeObjectURL(href); // 釋放掉blob對象
    }
  }, [listingDown]);

其他類型的文件也可以在前端這樣處理
項目踩坑 在此記錄

2020.4.15 更新:excel-export好像沒有ts的支持,編譯時會導致mongoose連接失敗 不清楚原因。改用了node-excel生成。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章