方法一:CsvExportor导出excel表格
一、安装
npm install --save csv-export
二、页面引入
import CsvExportor from 'csv-exportor'
三、导出数据
const exportdata = () => { // 导出方法
const exportlist = [
{name:'张三',age:'22',sex:'女',address:'地球'},
{name:'李四',age:'22',sex:'女',address:'火星'},
{name:'王五',age:'22',sex:'女',address:'未知'}
]
const header = ['姓名', '年龄', '性别', '地址']
CsvExportor.downloadCsv(exportlist, { header }, '人员登记表.csv')
}
方法二
//vue3
const tableToExcel = (function () {
/*
**两个参数
**table:table的id
**name:表格名称
*/
const mineType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
const template =
'<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
format = function (s: any, c: any) {
return s.replace(/{(\w+)}/g, function (m: any, p: any) {
return c[p];
});
};
return function (table: any, name: any) {
if (!table.nodeType) table = document.getElementById(table);
var ctx = { worksheet: name || "Worksheet", table: table.innerHTML };
download(format(template, ctx), name,mineType);
};
})();
//vue2
tableToExcel(table, name) {
const mineType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
const template =
'<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>';
const format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
if (!table.nodeType) table = document.getElementById(table);
var ctx = { worksheet: name || "Worksheet", table: table.innerHTML };
download(format(template, ctx), name,mineType);
}
const download= (data: Blob, fileName: string, mineType: string) => {
// 创建 blob
const blob = new Blob([data], { type: mineType });
// 创建 href 超链接,点击进行下载
window.URL = window.URL || window.webkitURL;
const href = URL.createObjectURL(blob);
const downA = document.createElement("a");
downA.href = href;
downA.download = fileName;
downA.click();
// 销毁超连接
window.URL.revokeObjectURL(href);
};