如何將JSON格式的數據轉化成excel?
總體思路就是json數據的key,value跟Excel的行列轉換,還有就是解決數據在Excel表格中存放的位置,區域問題。
要用到的兩個小插件,一個是xslx.js,一個是FileSaver.js,前者是來處理生成Excel的,後者是用來把文件下載保存到本地的。
以下是個小示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>導出生成excel</title>
<script src="js/xlsx.full.min.js"></script>
<script src="js/FileSaver.min.js"></script>
</head>
<body>
<button onclick="downloadExl(students)">導出</button>
<script>
var students = [{
"name": "姓名1",
"age": "8",
"sex": "男",
"height": "70"
}, {
"name": "姓名2",
"age": "9",
"sex": "男",
"height": "80"
}, {
"name": "小明3",
"age": "10",
"sex": "男",
"height": "100"
}];
function downloadExl(data, type) {
var keys = Object.keys(data[0]);
var firstRow = {};
keys.forEach(function (item) {
firstRow[item] = item;
});
data.unshift(firstRow);
var content = {};
// 把json格式的數據轉為excel的行列形式
var sheetsData = data.map(function (item, rowIndex) {
return keys.map(function (key, columnIndex) {
return Object.assign({}, {
value: item[key],
position: (columnIndex > 25 ? getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1),
});
});
}).reduce(function (prev, next) {
return prev.concat(next);
});
sheetsData.forEach(function (item, index) {
content[item.position] = { v: item.value };
});
//設置區域,比如表格從A1到D10,SheetNames:標題,
var coordinate = Object.keys(content);
var workBook = {
SheetNames: ["helloSheet"],
Sheets: {
"helloSheet": Object.assign({}, content, { "!ref": coordinate[0] + ":" + coordinate[coordinate.length - 1] }),
}
};
//這裡的數據是用來定義導出的格式類型
var excelData = XLSX.write(workBook, { bookType: "xlsx", bookSST: false, type: "binary" });
var blob = new Blob([string2ArrayBuffer(excelData)], { type: "" });
saveAs(blob, "hello.xlsx");
}
//字元串轉字元流
function string2ArrayBuffer(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
// 將指定的自然數轉換為26進位表示。映射關係:[0-25] -> [A-Z]。
function getCharCol(n) {
let temCol = "",
s = "",
m = 0
while (n > 0) {
m = n % 26 + 1
s = String.fromCharCode(m + 64) + s
n = (n - m) / 26
}
return s
}
</script>
</body>
</html>
推薦閱讀: