JS 读取excel文件内容 和 将json数据导出excel文件
一、实现将json数据导出为excel文件
1、通过原生js实现
核心方法:
function JSONToExcelConvertor(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) {
row += "<th align='center'>" + title[i] + '</th>';
}
}
else {
//不使用标题项
for (var i in arrData[0]) {
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) {
if (filter.indexOf(index) == -1) {
var value = arrData[i][index] == null ? "" : arrData[i][index];
row += '<td>' + value + '</td>';
}
}
else {
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);
}
JSONData:json数据
FileName:导出的文件名
title: 列的表头标题
filter: 要过滤的数据列
方法调用:
let excelData = [
{ "c1": "990019", "c2": "张三1", "c3": "女", },
{ "c1": "140007", "c2": "张三2", "c3": "女", },
]
JSONToExcelConvertor(excelData, "test", ['ID(编号)', 'NAME(名称)'], ['c3']);
2、通过xlsx.js实现
安装
方式一:命令行下载
npm install xlsx
方式二:github手动下载
https://github.com/SheetJS/sheetjs/tree/github/dist
<script type="text/javascript" src='./xlsx.full.min.js'></script>
使用
实现核心方法
/**
* 单个sheet下载
* @param {object[]} json json
* @param {object} tableTitle excel表头名称
* @param {string} fileName 文件名称
* @param {object} wbConfig 扩展
* @param {object} woptsConfig 扩展
*/
function json2Excel(json,tableTitle,fileName,wbConfig={},woptsConfig={}) {
let wopts = {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
};
let workBook = {
SheetNames: ['Sheet1'],
Sheets: {},
Props: {}
};
json = [tableTitle,...json];
workBook.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(json,{skipHeader:true}); // skipHeader 忽略原来的表头
//3、XLSX.write() 开始编写Excel表格
//4、changeData() 将数据处理成需要输出的格式
saveAs(new Blob([changeData(XLSX.write({...workBook,...wbConfig}, {...wopts,...woptsConfig}))], {type: 'application/octet-stream'}),fileName)
}
/**
* 多个sheet下载
* @param {object} data
* @param data.Sheet1.title {}
* @param data.Sheet1.data []
* @param {string} fileName 文件名称
* data格式
* {
'sheet1':{
title:{name:'名字',age:'年龄'},
json:[{name:'sd',age:1999}]
},
'sheet2':{
title:{name:'名字',age:'年龄'},
json:[{name:'z',age:195}]
},
}
*/
function json2ExcelMultiSheet(data,fileName){
let wopts = {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
};
let workBook = {
SheetNames: [],
Sheets: {},
Props: {}
};
let keys = Object.keys(data);
keys.forEach(key=>{
let json = [data[key].title,...data[key].json];
workBook.SheetNames.push(key);
workBook.Sheets[key] = XLSX.utils.json_to_sheet(json,{skipHeader:true}); // skipHeader 忽略原来的表头
})
// XLSX.write() 开始编写Excel表格
//changeData() 将数据处理成需要输出的格式
saveAs(new Blob([changeData(XLSX.write(workBook, wopts))], {type: 'application/octet-stream'}),fileName)
}
function changeData(s) {
//如果存在ArrayBuffer对象(es6) 最好采用该对象
if (typeof ArrayBuffer !== 'undefined') {
//1、创建一个字节长度为s.length的内存区域
let buf = new ArrayBuffer(s.length);
//2、创建一个指向buf的Unit8视图,开始于字节0,直到缓冲区的末尾
let view = new Uint8Array(buf);
//3、返回指定位置的字符的Unicode编码
for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
} else {
let buf = new Array(s.length);
for (let i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
}
function saveAs(obj, fileName) {//当然可以自定义简单的下载文件实现方式
let tmpa = document.createElement("a");
tmpa.download = fileName+'.xlsx' || "下载.xlsx";
tmpa.href = URL.createObjectURL(obj); //绑定a标签
tmpa.click(); //模拟点击实现下载
setTimeout(function () { //延时释放
URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
}, 100);
}
方法调用:
这里只演示单个sheet下载
let excelData = [
{ "c1": "990019", "c2": "张三1", "c3": "女", },
{ "c1": "140007", "c2": "张三2", "c3": "女", },
]
json2Excel(excelData, { "c1": "ID(编号)", "c2": "NAME(名称)", "c3": "c3", }, "test")
二、JS读取excel文件内容
这里使用了上面说的xlsx.js库,所以需先安装xlsx
先通过本地导入要读取的excel文件
<div id="import">
<p>导入模版</p>
<p> 请选择要选择导入的模版文件</p>
<input type="file" onchange="importFile(this)">
<div id="demo"></div>
</div>
将excel解析为json后写入元素
var wb;//读取完成的数据
var rABS = false; //是否将文件读取为二进制字符串
function importFile(obj) {//导入
if (!obj.files) {
return;
}
var f = obj.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
if (rABS) {
wb = XLSX.read(btoa(fixdata(data)), {//手动转化
type: 'base64'
});
} else {
wb = XLSX.read(data, {
type: 'binary'//以二进制的方式读取
});
}
console.log('wb: ', wb);
//wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
//wb.Sheets[Sheet名]获取第一个Sheet的数据
// XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], { raw: false }); //以字符串形式读取。
console.log('XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]): ', XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
document.getElementById("demo").innerHTML = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
};
if (rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
}
function fixdata(data) { //文件流转BinaryString
var o = "",
l = 0,
w = 10240;
for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
return o;
}
完美,成功解析:
参考资料:
https://www.npmjs.com/package/xlsx
https://blog.csdn.net/weixin_43660626/article/details/106780365