设置如下:我有一个主页,在那里我显示了一个从页面内部使用逗号分隔值构建的图表。我想让用户能够以cvs文件的形式下载数据,而不需要再次联系服务器。(因为数据已经在那里了)这是可能的吗?我更喜欢纯JavaScript解决方案。
到目前为止,我发现了:http://pixelgraphics.us/downloadify/test.html,但它涉及到flash,我想避免这种情况。
我无法想象以前没有人问过这个问题。我很抱歉重复发帖,但似乎我用错了关键字或别的什么-我还没有在这些论坛中找到解决方案。
发布于 2010-11-15 21:50:23
据我所知,这是不可能的:这就是Downloadify被创建的原因。
您可以尝试链接到包含CSV数据的data:URL
,但会出现跨浏览器的问题。
发布于 2010-11-15 22:39:43
function export(exportAs) {
var csvText = tableRowsToCSV(this.headTable.rows);
csvText += tableRowsToCSV(this.bodyTable.rows);
//open the iframe doc for writing
var expIFrame;
if (strBrowser == "MSIE") expIFrame = document.exportiframe;
else expIFrame = window.framesexportiframe;
var doc = expIFrame.document;
doc.open('text/plain', 'replace');
doc.charset = "utf-8";
doc.write(csvText);
doc.close();
var fileName = exportAs + ".txt";
doc.execCommand("SaveAs", null, fileName);
}
function tableRowsToCSV(theRows) {
var csv = "";
var csvRow = "";
var theCells;
var cellData = "";
for (var r = 0; r < theRows.length; r++) {
theCells = theRows.item(r).cells;
for (var c = 0; c < theCells.length; c++) {
cellData = "";
cellData = theCells.item(c).innerText;
if (cellData.indexOf(",") != -1) cellData = "'" + cellData + "'";
if (cellData != "") csvRow += "," + cellData;
}
if (csvRow != "") csvRow = csvRow.substring(1, csvRow.length);
csv += csvRow + "\n";
csvRow = "";
}
return csv;
}
我在别处找到了这段代码,here,之前
发布于 2013-04-25 19:03:04
如果您的用户拥有最新的浏览器,新的Blob对象可以为您提供帮助。
基于这里的示例https://developer.mozilla.org/en/docs/DOM/Blob ("Blob构造函数示例用法“),您可以执行如下操作:
var typedArray = "123,abc,456"; //your csv as a string
var blob = new Blob([typedArray], {type: "text/csv"});
var url = URL.createObjectURL(blob);
var a = document.querySelector("#linktocsv"); // the id of the <a> element where you will render the download link
a.href = url;
a.download = "file.csv";
https://stackoverflow.com/questions/4184944
复制相似问题