elTable 导出excel 及样式设置

511 阅读1分钟
import FileSaver from 'file-saver'import XLSX from 'xlsx'import XLSXS from 'xlsx-style'
首先要安装  file-saver,xlsx,xlsx-style
file-saver,xlsx是读写表格的,因为xlsx不能直接对 单元格进行样式设置 所以需要到 xlsx-style
//导出方法
function exportExcel(excelName) {      try {        // 先找到所在的el表格        let [el] = this.$children.filter((item) => {          return item.tableId        })        // el实例的Dom        const $e = el.$el        // 如果表格加了fixed属性,则导出的文件会生产两份一样的数据,所以可在这里判断一下        let $table = $e.querySelector('.el-table__fixed')        if (!$table) {          $table = $e        }        // 为了返回单元格原始字符串,设置{ raw: true }        const wb = XLSX.utils.table_to_book($table, { raw: true })        // Sheet1 如果取不到可以 log 下 wb 查找        setExlStyle(wb['Sheets']['Sheet1']) // 设置列宽 字号等        addRangeBorder(wb['Sheets']['Sheet1']['!merges'], wb['Sheets']['Sheet1'])        const wbout = XLSXS.write(wb, {          type: 'buffer'        })        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${excelName || el.$parent.titleName || '新建Excel表格'}.xlsx`)      } catch (e) {        if (typeof console !== 'undefined') console.error(e)      }    }
//样式设置function setExlStyle(data) {  // console.log('data:', data)  data['!cols'] = []  for (let key in data) {    if (data[key] instanceof Object) {      // 其余配置可以去 源文档查找 Cell Styles      data[key].s = {        //边框线        border: {          top: {            style: 'thin'          },          bottom: {            style: 'thin'          },          left: {            style: 'thin'          },          right: {            style: 'thin'          }        },        font: {          sz: 12        },        //水平居中对齐        alignment: {          horizontal: 'center',          vertical: 'center'        }      }      // 列宽      data['!cols'].push({ wpx: 100 })    }  }  return data}function addRangeBorder(range, ws) {  let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']  range.forEach((item) => {    let startRow = Number(item.s.c),      endRow = Number(item.e.c)    for (let i = startRow + 1; i <= endRow; i++) {      ws[arr[i] + (Number(item.e.r) + 1)] = { s: { border: { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } } } }    }  })  return ws}

源文档: github.com/protobi/js-…