1、前端数据
①、初始化数据
1 var data = [
2 { id: 12, name: "张三", age: 12 }, { id: 13, name: "李四", age: 13 }, { id: 14, name: "王五", age: 14 },
3 { id: 15, name: "赵六", age: 15 }
4 ];
2、构建表格样式
①、表结构
1 var table = '<table border="1px" cellspacing="0" cellpadding="0">';
2 table += '<thead>';
3 table += '<th>日期</th>';
4 table += '<th>name</th>';
5 table += '<th>age</th>';
6 table += '<th>sex</th>';
7 table += '</thead>';
8 table += '<tbody>';
9
10
11 var _body = "";
12 for (var row = 0; row < data.length; row++) {
13 _body += '<tr>';
14 _body += '<td>';
15 _body += `${data[row].id}`;
16 _body += '</td>';
17 _body += '<td>';
18 _body += `${data[row].name}`;
19 _body += '</td>';
20 _body += '<td>';
21 _body += `${data[row].age}`;
22 _body += '</td>';
23 _body += '</tr>';
24 }
25 table += _body;
26 table += '</tbody>';
27 table += '</table>';
28 excel(table, "excel.xlsx");
3、导出表格
①、编写导出表格方法
function excel(data, filename) {
var html =
"<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'>";
html += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
html += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
html += '; charset=UTF-8">';
html += "<head>";
html += "</head>";
html += "<body>";
html += data;
html += "</body>";
html += "</html>";
var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(html);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = `${filename}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
4、ajax下载文件
$.ajax({
url: "https://domain/api/stream",
type: "get",
data: {},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', `Bearer ${token}`)
},
contentType: "application/octet-stream",
xhrFields: {
responseType: "arraybuffer",//响应类型为文件流
},
success: function (rest) {
//将byte转换成Blob
const file = window.URL.createObjectURL(new Blob([rest], { type: "application/vnd.ms-excel;charset=utf-8" }));
let a = document.createElement('a')
a.href =file
a.download = "fileName.xlsx"
a.click()
}
});
本文详细介绍了一种使用前端技术将数据转化为Excel表格并实现下载的方法。首先,通过JavaScript初始化数据,接着构建HTML表格结构,然后利用特定的HTML与元信息格式化数据,最后通过Ajax调用API获取文件流或直接生成Excel文件进行下载。
2万+

被折叠的 条评论
为什么被折叠?



