安装xlsx插件
npm i xlsx -S
使用
import XLSX from "xlsx"
export const exportExcel = (tableName, excelName) => {
const wb = XLSX.utils.table_to_book(document.querySelector(`#${tableName}`), {
raw: true // 使用原始字符串(例如不想对"%"进行转换时使用)
});
/* 获取二进制字符串作为输出 */
const wbout = XLSX.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
downloadExcel(wbout, excelName);
}
/**
* 下载Excel文件流
* @param {string} binaryData
* @param {string} fileName
*/
export const downloadExcel = (binaryData, fileName) => {
const a = document.createElement("a");
a.download = fileName;
a.style.display = "none";
a.href = URL.createObjectURL(new Blob([binaryData], { type: 'application/vnd.ms-excel' }));
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}
详情参考 npm文档