element table 导出excel并设置excel样式列宽

安装:

npm i —S xlsx file-saver

npm install xlsx-style --save

引用:

import FileSaver from 'file-saver'

import XLSX from 'xlsx'

import XLSXStyle from "xlsx-style";

注:引入XLSXStyle会报错,解决方法有两种

1.直接改源码,在\node_modules\xlsx-style\dist\cpexcel.js,var cpt = require('./cpt' + 'able');  改为   var cpt = cptable;

2.在vue的config文件中加如下代码:'./cptable': 'var cptable'

公共方法提一个单独文件xlsxFileSaver.js:

import FileSaver from 'file-saver'
import XLSX from 'xlsx'

export function exportToExcel(tableId,fileName,widthArr){
    // const XLSX = require('xlsx')
    // return
    // 使用 this.$nextTick 是在dom元素都渲染完成之后再执行
    // 设置导出的内容是否只做解析,不进行格式转换     false:要解析, true:不解析
    const xlsxParam = { raw: true }
    const ws = XLSX.utils.table_to_sheet(document.getElementById(tableId))
    console.log(document.getElementById(tableId))
    let wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
    // const wb = XLSX.utils.table_to_book(document.querySelector('#'+tableId), xlsxParam)
    // 导出excel文件名
    // let fileName = '营业收入' + new Date().getTime() + '.xlsx'
    console.log(wb['Sheets']['Sheet1'])
    setExlStyle(wb['Sheets']['Sheet1'],widthArr);
    addRangeBorder(wb['Sheets']['Sheet1']['!merges'],wb['Sheets']['Sheet1'])
    // const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
    const wbout = XLSXStyle.write(wb, { type: 'buffer'})

    try {
      // 下载保存文件
      FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), fileName + '.xlsx')
    } catch (e) {
      if (typeof console !== 'undefined') {
        // console.log(e, wbout)
      }
    }
    return wbout

  }
//设置样式
  function setExlStyle(data,widthArr) {
    console.log(data)
    let borderAll = {  //单元格外侧框线
      top: {
        style: 'thin',
      },
      bottom: {
        style: 'thin'
      },
      left: {
        style: 'thin'
      },
      right: {
        style: 'thin'
      }
    };
    data['!cols'] = [];
    for (let key in data) {
      // console.log(data[key])
      console.log(key)
      if (data[key] instanceof Object) {
        if(key=='A1'){
          data[key].s = {
            border: borderAll,
            alignment: {
              wrapText: 1,//自动换行
              horizontal: 'center',   //水平居中对齐
              vertical:'center'
            },
            font:{
              sz:11
            },
            bold:true,
            numFmt: 0,
          }
        }else{
          data[key].s = {
            border: borderAll,
            alignment: {
              wrapText: 1,//自动换行
              horizontal: 'left',   //水平居中对齐
              vertical:'center'
            },
            font:{
              sz:11
            },
            bold:true,
            numFmt: 0,
          }
        }
        
        // data['!cols'].push({wpx: 100});
      }
    }
    for(let i in widthArr){
      data['!cols'][i]={wpx: widthArr[i]};
    }
    console.log(data)
    return data;
  }
//合并单元格
  function addRangeBorder (range, ws) {
      let cols = ["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 => {
        console.log(item)
        let style = {
          s: {
            border: {
              top: { style: 'thin' },
              left: { style: 'thin' },
              bottom: { style: 'thin' },
              right: { style: 'thin' }
            }
          }
        }
        // 处理合并行
        for (let i = item.s.c; i <= item.e.c; i++) {
          ws[`${cols[i]}${Number(item.e.r) + 1}`] = ws[`${cols[i]}${Number(item.e.r) + 1}`] || style
          // 处理合并列
          for (let k = item.s.r + 2; k <= item.e.r + 1; k++) {
            ws[cols[i] + k] = ws[cols[k] + item.e.r] || style
          }
        }
      })
      return ws;
  }

文件中导入方法:

import {exportToExcel} from '@/utils/xlsxFileSaver'

使用:

exportToExcel(id,name,widthArr)

注:仅可导出当前页,如需导出所有数据可以单独写个table

你可能感兴趣的:(前端,javascript,前端,vue.js)