具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>
<script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<title>下载Excel</title>
</head>
<body>
<button onclick="downloadfile()">下载Excel</button>
<script>
function downloadfile() {
var workbook = XLSX.utils.book_new(); //这段代码创建了一个名为的Workbook对象。
console.log(workbook)
var ws = XLSX.utils.json_to_sheet([]); //创建一个工作表对象
var ws1 = XLSX.utils.json_to_sheet([]); //创建一个工作表对象
XLSX.utils.book_append_sheet(workbook,ws,"ph数据"); //将工作表添加到workbook对象中
XLSX.utils.book_append_sheet(workbook,ws1,"test"); //将工作表添加到workbook对象中
workbook.creator = 'test123' //创建者
workbook.created = new Date() //创建时间
var data = [
{"bz":"","cqqk":"/","date":"2023-01-04","djperson":"zs","id":1,"name":"2#","ph":5.8},{"bz":"","cqqk":"/","date":"2023-01-04","djperson":"zs","id":2,"name":"3#","ph":5.06}
]
var jsonDataWithHeaders = [
{ "header1": "value1", "header2": "value2" },
{ "header1": "value3", "header2": "value4" }
];
var datas = []
for(var i = 0;i < data.length; i++){
var p = {"id":data[i].id,"date":data[i].date,"name":data[i].name,"ph":data[i].ph,"cqqk":data[i].cqqk,"djperson":data[i].djperson,"bz":data[i].bz}
datas.push(p)
}
//
//将数据添加到工作表
XLSX.utils.sheet_add_json(ws,datas,{skipHeader:false,origin:"A1"})
XLSX.utils.sheet_add_json(ws1,jsonDataWithHeaders,{skipHeader:true,origin:"A2"})
var date = new Date();
var isoString = '导出数据'+ date.toISOString().slice(0,10);
// console.log(p);
// const date = new Date();
// // 获取年份
// const year = date.getFullYear().toString();
// // 获取月份,月份从0开始,需要加1
// const month = (date.getMonth() + 1).toString();
// // 获取日期
// const day = date.getDate().toString();
// 获取小时
const hours = date.getHours().toString().padStart(2, '0');
// 获取分钟padStart(2, '0')在前面补0
const minutes = date.getMinutes().toString().padStart(2, '0');
// 获取秒数
const seconds = date.getSeconds().toString().padStart(2, '0');
var sfm = hours+':'+minutes+':'+seconds
var names = isoString+' '+sfm+'.xlsx'
console.log(names);
//导出Excel文件
XLSX.writeFile(workbook,names)
}
</script>
</body>
</html>
这个建了一个Excel表,两个sheet,分别存放了一定的数据,最后进行下载下来,其中skipHeader:false,origin:"A1"代表不省略表头,表头默认是字典中的keys,从A1行开始:
转载自CSDN-专业IT技术社区
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_33267306/article/details/142762434