web实现下载excel文件(exceljs、file-save

2021-10-10  本文已影响0人  林思念
1、导入模块
import Excel from 'exceljs'                    // excel解析模块
import FileSaver from 'file-saver'          
2、解析excel文件,获取数据
let workbook = new Excel.Workbook()            // 创建excel文件对象
let reader = new FileReader()                    
reader.readAsArrayBuffer(file)                 // <input type="file" />
reader.onloadend = function (event) {
  let arrayBuffer = reader.result
  workbook.xlsx.load(arrayBuffer).then(function (workbook) {
    let sheet = workbook.getWorksheet(1)       // 获取第一个sheet
    if (sheet) {
      workbook.worksheets[0].eachRow(function (row, rowNumber) {
        if (rowNumber > 1) {
          let customreName = row.values[1] 
          let address = row.values[2] 
          customreName = customreName.trim().replace(/\n/g, '')
          address = address.trim().replace(/\n/g, '') 

          locations.push({
            customreName: customreName,
            address: address
          })                                    // 得到的数据
        }
      }) 
    }
  })
}    
3、将数据写入excel,得到excel文件
const workbook = new Excel.Workbook();              // 创建文件
const sheet = workbook.addWorksheet("My Sheet");    // 创建表
sheet.columns = [                                   // 设置表头
  { header: '客户名称', key: 'customreName', width: 40, style: { font: { size: 14 } } },    // 表头,对应数据属性为`key`值
  { header: '客户地址', key: 'address', width: 40, style: { font: { size: 14 } } },
  { header: '联系人姓名', key: 'contractName', width: 20, style: { font: { size: 14 } } },
  { header: '联系人电话', key: 'contractTelPhone', width: 20, style: { font: { size: 14 } } }
];
sheet.addRows(records)     // 将对应的数据添加进workbook对象
workbook.xlsx.writeBuffer().then((result) => {
  const blob = new Blob([result], { type: "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
  FileSaver.saveAs(blob, 'xxxx.xlsx')
})
上一篇下一篇

猜你喜欢

热点阅读