前段时间,我们项目提出一个前端导出Excel表格的需求,
这个很简单,利用xlsx,file-saver很容易实现(网上很多教程)。
后来需要加入标题,标题居中显示,加入边框等等样式需求,这就给我很多困扰,查阅大量资料和研究,最终选定xlsx-style进行修改(借鉴https://www.jianshu.com/p/23ee264ecde8)。
以下便是xlsx-style踩坑之旅:
导入问题cnpm install --save xlsx-style
import XLSX from "xlsx-style"报错:This relative module was not found: ./cptable in ./node_modules/xlsx-style@0.8.13@xlsx-style/dist/cpexcel.js
需要修改源码:
在\node_modules\xlsx-style\dist\cpexcel.js 807行 的 var cpt = require(’./cpt’ + ‘able’); 改成 var cpt = cptable;
本地src目录新建vendor/Export2Excel.js:
/* eslint-disable */
require('script-loader!file-saver');
import XLSX from 'xlsx-style'
function generateArray(table) {
var out = [];
var rows = table.querySelectorAll('tr');
var ranges = [];
for (var R = 0; R < rows.length; ++R) {
var outRow = [];
var row = rows[R];
var columns = row.querySelectorAll('td');
for (var C = 0; C < columns.length; ++C) {
var cell = columns[C];
var colspan = cell.getAttribute('colspan');
var rowspan = cell.getAttribute('rowspan');
var cellValue = cell.innerText;
if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
//Skip ranges
ranges.forEach(function (range) {
if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
}
});
//Handle Row Span
if (rowspan || colspan) {
rowspan = rowspan || 1;
colspan = colspan || 1;
ranges.push({
s: {
r: R,
c: outRow.length
},
e: {
r: R + rowspan - 1,
c: outRow.length + colspan - 1
}
});
}
;
//Handle Value
ou