vue-纯前端实现数据导出excel

1、 使用xlsx。

  npm install xlsx --save
  • 页面调用
// table.vue
     <el-table id="tableExcel_Day" :data="tableData" border stripe :height="chatrsTableHeight">
         <el-table-column label="时间" align="center" prop="time" />
         <el-table-column label="数据质量" align="center" prop="quality" />
         <el-table-column :label="valueLabel" align="center" prop="value" />
     </el-table>
     <el-button size="mini" @click="exportxlsbtn">导出</el-button>
//js
   import XLSX from 'xlsx'
    exportxlsbtn(){
         const workbook = XLSX.utils.table_to_book(document.getElementById('tableExcel_Day'), { raw: true })
         const sheet = workbook.Sheets.Sheet1
    
         //设置列的宽度,上方table中只有三列,需根据实际情况来
         const wscols = [{ wch: 40 }, { wch: 40 }, { wch: 40 }]
         sheet['!cols'] = wscols
   
        //writeFile方法,在浏览器环境下会尝试强制客户端自动下载
       XLSX.writeFile(workbook, 'biaoge.xlsx', { bookType: 'xlsx', bookSST: true, type: 'array' })
}

2、 使用xlsx + file-saver

  npm install xlsx file-saver --save
  • 页面调用
 // table.vue
     <el-table id="tableExcel_Day" :data="tableData" border stripe :height="chatrsTableHeight">
         <el-table-column label="时间" align="center" prop="time" />
         <el-table-column label="数据质量" align="center" prop="quality" />
         <el-table-column :label="valueLabel" align="center" prop="value" />
     </el-table>
     <el-button size="mini" @click="exportxlsbtn">导出</el-button>
//js
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
    exportxlsbtn(){
             // 导出
    const xlsxParam = { raw: true } // 导出的内容只做解析,不进行格式转换
    const wb = XLSX.utils.table_to_book(document.querySelector('#tableExcel_Day'), xlsxParam)

    /* get binary string as output */
    const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
    try {
      FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `历史数据${this.historyDialogTitle}.xlsx`)
    } catch (e) {
      if (typeof console !== 'undefined') {
        console.log(e, wbout)
      }
    }
    return wbout
}
Logo

前往低代码交流专区

更多推荐