工作中,需要導出一個表格,後端直接傳回的list資料,需要前端自己導出。這時候我們可以使用插件;
可以在項目的package.json的dependencies加入一句 "xlsx": "^0.16.9",然後下載下傳,也可以直接 npm install xlsx --save;
在使用的時候,需要對插件進行改造,下面根據網上的改造做了一些改變,之前的改造,我在使用的時候出現了一些bug,當導出的列超過26行時候,導出的表格資料錯亂。我這裡改動後,可以擴充到52列,至于再多的列,也需要根據自己的需要再改造。
// excelUtil.js
import XLSX from 'xlsx';
function importExcel(file) {
// 擷取上傳的檔案對象
const { files } = file.target;
// 通過FileReader對象讀取檔案
const fileReader = new FileReader();
fileReader.onload = event => {
try {
const { result } = event.target;
// 以二進制流方式讀取得到整份excel表格對象
const workbook = XLSX.read(result, { type: 'binary' });
let data = []; // 存儲擷取到的資料
// 周遊每張工作表進行讀取(這裡預設隻讀取第一張表)
// eslint-disable-next-line no-restricted-syntax
for (const sheet in workbook.Sheets) {
// eslint-disable-next-line no-prototype-builtins
if (workbook.Sheets.hasOwnProperty(sheet)) {
// 利用 sheet_to_json 方法将 excel 轉成 json 資料
data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
// break; // 如果隻取第一張表,就取消注釋這行
}
}
console.log(data);
} catch (e) {
// 這裡可以抛出檔案類型錯誤不正确的相關提示
console.log('檔案類型不正确');
}
};
// 以二進制方式打開檔案
fileReader.readAsBinaryString(files[0]);
}
// 此法能将excel從26擴充成52行
function computedPosition(i) {
let d = '';
if (i < 26) {
d = String.fromCharCode(65 + i) + 1;
} else {
d = String.fromCharCode(65) + String.fromCharCode(65 - 26 + i) + 1;
}
return d;
}
// 計算列的位置
function computedPositionY(i) {
let d = '';
if (i < 26) {
d = String.fromCharCode(65 + i);
} else {
d = String.fromCharCode(65) + String.fromCharCode(65 - 26 + i);
}
return d;
}
function exportExcel(headers, data, fileName = '記錄表.xlsx') {
const _headers = headers
.map((item, i) =>
Object.assign({}, { key: item.key, title: item.title, position: computedPosition(i) })
)
.reduce(
(prev, next) =>
Object.assign({}, prev, { [next.position]: { key: next.key, v: next.title } }),
{}
);
const _data = data
.map((item, i) =>
headers.map((key, j) =>
Object.assign({}, { content: item[key.key], position: computedPositionY(j) + (i + 2) })
)
)
// 對剛才的結果進行降維處理(二維數組變成一維數組)
.reduce((prev, next) => prev.concat(next))
// 轉換成 worksheet 需要的結構
.reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.content } }), {});
// 合并 headers 和 data
const output = Object.assign({}, _headers, _data);
// 擷取所有單元格的位置
const outputPos = Object.keys(output);
// 計算出範圍 ,["A1",..., "H2"]
const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;
// 建構 workbook 對象
const wb = {
SheetNames: ['mySheet'],
Sheets: {
mySheet: Object.assign({}, output, {
'!ref': ref,
'!cols': [
// { wpx: 150 },
// { wpx: 150 },
// { wpx: 300 },
// { wpx: 200 },
// { wpx: 200 },
// { wpx: 200 },
// { wpx: 200 },
// { wpx: 300 },
],
}),
},
};
// 導出 Excel
XLSX.writeFile(wb, fileName);
}
export default { importExcel, exportExcel };
使用的時候:
import ExcelUtil from '@/utils/excelUtil';
ExcelUtil.exportExcel(column, InfoList, `xxx.xlsx`);
// 三個參數,和ant design 的表頭,表資料相似
// column:{title:string,key:string,dataIndex:string}[] ,表單的表頭
// InfoList:表資料
// 表名稱