JS实现纯前端将数据导出Excel两种方式亲测有效
程序员文章站
2022-05-31 09:15:44
...
由于项目需要,需要在不调用后台接口的情况下,将json数据导出到excel表格,参考了好多资料以及很多大佬写的博客终于实现,兼容chrome没问题,其他还没有测试过,这边介绍两种实现方式,并附上代码和gif动图,博主不才还望轻喷,代码可直接copy运行
方法一
将table标签,包括tr、td等对json数据进行拼接,将table输出到表格上实现,这种方法的弊端在于输出的是伪excel,虽说生成xls为后缀的文件,但文件形式上还是html,代码如下:
<html>
<meta charset="UTF-8">
<head>
<p style="font-size: 20px;color: red;">使用table标签方式将json导出xls文件</p>
<button onclick='tableToExcel()'>导出</button>
</head>
<body>
<script>
const tableToExcel = () => {
// 要导出的json数据
const jsonData = [
{
name:'路人甲',
phone:'123456',
email:'[email protected]'
},
{
name:'炮灰乙',
phone:'123456',
email:'[email protected]'
},
{
name:'土匪丙',
phone:'123456',
email:'[email protected]'
},
{
name:'流氓丁',
phone:'123456',
email:'[email protected]'
},
]
// 列标题
let str = '<tr><td>姓名</td><td>电话</td><td>邮箱</td></tr>';
// 循环遍历,每行加入tr标签,每个单元格加td标签
for(let i = 0 ; i < jsonData.length ; i++ ){
str+='<tr>';
for(const key in jsonData[i]){
// 增加\t为了不让表格显示科学计数法或者其他格式
str+=`<td>${ jsonData[i][key] + '\t'}</td>`;
}
str+='</tr>';
}
// Worksheet名
const worksheet = 'Sheet1'
const uri = 'data:application/vnd.ms-excel;base64,';
// 下载的表格模板数据
const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
<x:Name>${worksheet}</x:Name>
<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
</head><body><table>${str}</table></body></html>`;
// 下载模板
window.location.href = uri + base64(template);
};
// 输出base64编码
const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
</script>
</body>
</html>
方法二
通过将json遍历进行字符串拼接,将字符串输出到csv文件,代码如下:
<html>
<head>
<p style="font-size: 20px;color: red;">使用a标签方式将json导出csv文件</p>
<button onclick='tableToExcel()'>导出</button>
</head>
<body>
<script>
const tableToExcel = () => {
// 要导出的json数据
const jsonData = [
{
name:'路人甲',
phone:'123456789',
email:'[email protected]'
},
{
name:'炮灰乙',
phone:'123456789',
email:'[email protected]'
},
{
name:'土匪丙',
phone:'123456789',
email:'[email protected]'
},
{
name:'流氓丁',
phone:'123456789',
email:'[email protected]'
},
];
// 列标题,逗号隔开,每一个逗号就是隔开一个单元格
let str = `姓名,电话,邮箱\n`;
// 增加\t为了不让表格显示科学计数法或者其他格式
for(let i = 0 ; i < jsonData.length ; i++ ){
for(const key in jsonData[i]){
str+=`${jsonData[i][key] + '\t'},`;
}
str+='\n';
}
// encodeURIComponent解决中文乱码
const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
// 通过创建a标签实现
const link = document.createElement("a");
link.href = uri;
// 对下载的文件命名
link.download = "json数据表.csv";
link.click();
}
</script>
</body>
</html>
封装成方法
function exportExcel(JSONData, FileName, title, filter) {
if (!JSONData) return;
//转化json为object
var arrData = typeof JSONData != "object" ? JSON.parse(JSONData) : JSONData;
var excel = "<table>";
//设置表头
var row = "<tr>";
if (title) { //使用标题项
for (var i in title) {
if (filter.indexOf(i) == -1) {
row += "<th align='center'>" + title[i] + "</th>";
}
}
} else {//不使用标题项
for (var i in arrData[0]) {
if (filter.indexOf(i) == -1) {
row += "<th align='center'>" + i + "</th>";
}
}
}
excel += row + "</tr>";
//设置数据
for (var i = 0; i < arrData.length; i++) {
var row = "<tr>";
for (var index in arrData[i]) {
if (filter.indexOf(index) == -1) {
var value = arrData[i][index] == null ? "" : arrData[i][index];
row += "<td align='center'>" + value + "</td>";
}
}
excel += row + "</tr>";
}
excel += "</table>";
var excelFile =
"<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
excelFile +=
'<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
excelFile +=
'<meta http-equiv="content-type" content="application/vnd.ms-excel';
excelFile += '; charset=UTF-8">';
excelFile += "<head>";
excelFile += "<!--[if gte mso 9]>";
excelFile += "<xml>";
excelFile += "<x:ExcelWorkbook>";
excelFile += "<x:ExcelWorksheets>";
excelFile += "<x:ExcelWorksheet>";
excelFile += "<x:Name>";
excelFile += "{worksheet}";
excelFile += "</x:Name>";
excelFile += "<x:WorksheetOptions>";
excelFile += "<x:DisplayGridlines/>";
excelFile += "</x:WorksheetOptions>";
excelFile += "</x:ExcelWorksheet>";
excelFile += "</x:ExcelWorksheets>";
excelFile += "</x:ExcelWorkbook>";
excelFile += "</xml>";
excelFile += "<![endif]-->";
excelFile += "</head>";
excelFile += "<body>";
excelFile += excel;
excelFile += "</body>";
excelFile += "</html>";
var uri =
"data:application/vnd.ms-excel;charset=utf-8," +
encodeURIComponent(excelFile);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = FileName + ".xls";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}