javascript 将javascript数据保存到Excel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17868643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save javascript data to Excel
提问by tbogatchev
I have a web application that needs to be able to export some javascript data (arrays, mostly) to Microsoft Excel. I've been told the best way to do that is to save my data as a CSV file. I know there are a lot of threads that deal with similar issues, but so far I have not found exactly what I am looking for... I would like to get around calling a web service and do this through the client side.
我有一个需要能够将一些 javascript 数据(主要是数组)导出到 Microsoft Excel 的 Web 应用程序。有人告诉我最好的方法是将我的数据保存为 CSV 文件。我知道有很多线程处理类似的问题,但到目前为止我还没有找到我正在寻找的内容......我想绕过调用 Web 服务并通过客户端执行此操作。
Following some suggestions I tried writing my arrays to disk using data URIs. Here is the code that I have in javascript:
按照一些建议,我尝试使用数据 URI 将我的数组写入磁盘。这是我在 javascript 中的代码:
function exportToCsv() {
var data = [JSONdata.mass, JSONdata.waterMass, JSONdata.bedTemp, JSONdata.evapRate];
var keys = ["Mass(kg)", "H2O Mass in Bed(kg)", "Bed Temperature(kg)", "Evaporation Rate"];
var str;
var orderedData = [];
for (var i = 0, iLen = data.length; i < iLen; i++) {
temp = data[i];
for (var j = 0, jLen = temp.length; j < jLen; j++) {
if (!orderedData[j]) {
orderedData.push([temp[j]]);
} else {
orderedData[j].push(temp[j]);
}
}
}
str = keys.join(',') + '\r\n' + orderedData.join('\r\n');
var uri = 'data:application/csv;charset=UTF-8,' + str;
window.open(uri);
}
The string str
looks like its in CSV format, but when I save my file, it turns up empty.
I also would very much like to save the contents of str
to a CSV file from a pop-up prompt.
该字符串str
看起来像 CSV 格式,但是当我保存文件时,它变成空的。我也非常想str
从弹出提示中将 的内容保存到 CSV 文件中。
I looked into Downloadify and FileSaver.js, but had trouble finding good documentation. This seems like it should be a fairly easy thing to do... Please lend a hand!
我查看了 Downloadify 和 FileSaver.js,但找不到好的文档。这看起来应该是一件相当容易的事情......请伸出援手!
Thanks in advance!
提前致谢!
EDIT/UPDATE
编辑/更新
I ended up getting my solution to work using FileSaver.js. My data was a header followed by four large double arrays, so CVS was a good enough format for me. Here is the code I used to get my CSV files to save properly:
我最终使用FileSaver.js获得了我的解决方案。我的数据是一个标题,后跟四个大的双数组,所以 CVS 对我来说是一个足够好的格式。这是我用来正确保存 CSV 文件的代码:
function exportExcel()
{
var data = [JSONdata.mass, JSONdata.waterMass, JSONdata.bedTemp, JSONdata.evapRate];
//var data = [[1,2,3,4,5],[11,22,33,44,55],[111,222,333,444,555],[1111,2222,3333,4444,5555]];
var keys = ['"Mass(kg)"', '"H2O Mass in Bed(kg)"', '"Bed Temperature(kg)"', '"Evaporation Rate"'];
var convertToCSV = function(data, keys) {
var orderedData = [];
for (var i = 0, iLen = data.length; i < iLen; i++) {
temp = data[i];
for (var j = 0, jLen = temp.length; j < jLen; j++) {
quotes = ['"'+temp[j]+'"'];
if (!orderedData[j]) {
orderedData.push([quotes]);
} else {
orderedData[j].push(quotes);
}
}
}
return keys.join(',') + '\r\n' + orderedData.join('\r\n');
}
var str = convertToCSV(data, keys);
var blob = new Blob([str], {type: "text/plain;charset=utf-8"});
var filename = prompt("Please enter the filename");
if(filename!=null && filename!="")
saveAs(blob, [filename+'.csv']);
else
alert("please enter a filename!");
}
If anyone else comes across a similar issue, this solution worked pretty well for me and allowed me to skip going back to the server side. Thanks for the help everyone.
如果其他人遇到类似的问题,这个解决方案对我来说效果很好,让我可以跳过回到服务器端。谢谢大家的帮助。
回答by juan.facorro
I was able to understand and reproduce the behavior you are describing. The problem with the code that generates the URI is that it's not encoding the contents of str
.
我能够理解并重现您所描述的行为。生成 URI 的代码的问题在于它没有对str
.
Here's the line that I changed, notice the wrapping of the str
variable with the encodeURI()
built-in function:
这是我更改的行,注意str
使用encodeURI()
内置函数包装变量:
var uri = 'data:application/csv;charset=UTF-8,' + encodeURI(str);
Here's a fiddle that generates the CSV file with the new lines included: DEMO. I simplified the for
loop since orderedData
turned out empty after its execution.
这是一个生成包含新行的 CSV 文件的小提琴:DEMO。我简化了for
循环,因为orderedData
它在执行后变成空的。
Note that Excel generated "CSV" files, don't actually use commas but semicolons. So if you want to use the file in Excel, replace ,
for ;
. Here's an Excel compatible file generation: DEMO.
请注意,Excel 生成的“CSV”文件实际上不使用逗号而是使用分号。所以,如果你想使用Excel文件,替换,
了;
。这是 Excel 兼容的文件生成:DEMO。
回答by krishnakid
Easy way to turn Javascript array into comma-separated list?
将 Javascript 数组转换为逗号分隔列表的简单方法?
seems to be a good thread on this, and a relatively straightforward implementation of the functionality you want.
似乎是一个很好的线程,并且是您想要的功能的相对简单的实现。
Is there some reason this did not work for you?
有什么原因这对你不起作用吗?
EDIT:
编辑:
It seems like you are interested in the HTML5 FileSaver, though I do not know how widely this is supported, it would seem to fulfill your functionality.
看起来您对 HTML5 FileSaver 感兴趣,虽然我不知道它的支持范围有多广,但它似乎可以满足您的功能。
this: http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side
这个:http: //updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side
and this: How can i generate a file and offer it for download in plain javascript?