【发布时间】:2015-05-07 17:02:01
【问题描述】:
我有 Json 数据,我需要使用 javascript 将 json 数据转换为 Excel 文件,
参考网址:http://jsfiddle.net/hybrid13i/JXrwM/
我正在使用此代码:
function JSONToTSVConvertor(JSONData, ReportTitle, ShowLabel, myTemplateName){
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var TSV = '';
//Set Report title in first row or line
//TSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and tab-seprated
row += index + ' ';
}
row = row.slice(0, -1);
//append Label row with line break
TSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string tab-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '" ';
}
row.slice(0, row.length - 1);
//add a line break after each row
TSV += row + '\r\n';
}
if (TSV == '') {
alert("Invalid data");
return;
}
var blob = new Blob([TSV], {type: "data:text/tsv;charset=utf-8"});
//Generate a file name
var fileName = myTemplateName;
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");
saveAs(blob, ""+fileName+".tsv");
}
此示例代码适用于 csv 和 tsv 格式。我需要 Excel 格式我不认为有任何想法请帮助我。 请建议一些示例代码。 谢谢...
【问题讨论】:
-
.csv格式已经是excel文件
-
@AndyChen,不完全是,.csv 格式可以在 Excel 中打开,但这并不意味着它是一个 excel 文件..
-
我正在尝试转换 .xlsx 文件
-
我错了,是“逗号分隔值”文件,但是可以用excel打开。
-
如果您不介意使用 API json-xls API
标签: javascript json