Javascript:从页面内的内容将数据下载到文件

问题描述 投票:0回答:8

设置如下: 我有一个主页,其中显示一个使用页面内逗号分隔值构建的图表。我想让用户能够将数据下载为 cvs 文件,而无需再次联系服务器。 (因为数据已经存在) 这有可能吗?我更喜欢纯 JavaScript 解决方案。

到目前为止我发现:http://pixelgraphics.us/downloadify/test.html但它涉及我想避免的闪光灯。

我无法想象这个问题以前没有被问过。很抱歉重复发帖,但似乎我使用了错误的关键字或其他内容 - 我在这些论坛中没有找到解决方案。

javascript file download local
8个回答
36
投票

在 Safari 5、Firefox 6、Opera 12、Chrome 26 上测试。

<a id='a'>Download CSV</a>
<script>
    var csv = 'a,b,c\n1,2,3\n';
    var a = document.getElementById('a');
    a.href='data:text/csv;base64,' + btoa(csv);
</script>

HTML5

<a id='a' download='Download.csv' type='text/csv'>Download CSV</a>
<script>
    var csv = 'a,b,c\n1,2,3\n';
    var data = new Blob([csv]);
    var a = document.getElementById('a');
    a.href = URL.createObjectURL(data);
</script>

32
投票

简单的解决方案:

function download(content, filename, contentType)
{
    if(!contentType) contentType = 'application/octet-stream';
        var a = document.createElement('a');
        var blob = new Blob([content], {'type':contentType});
        a.href = window.URL.createObjectURL(blob);
        a.download = filename;
        a.click();
}

用法

download("csv_data_here", "filename.csv", "text/csv");

13
投票

更新

时间确实会改变一切;-) 当我第一次回答这个问题时,IE8是最新的 IE 浏览器(2010 年 11 月),因此没有跨浏览器的方法来完成此任务,无需往返服务器或使用工具需要闪光灯。

@Zectbumo 的回答将为您提供您现在需要的内容,但是对于历史背景,请注意哪些 IE 浏览器支持哪些功能。

  • btoa() 在 IE8 和 IE9 中未定义
  • Blob 在 IE10+ 中可用

请务必在您需要支持的浏览器中进行测试。尽管另一个答案中的 Blob 示例应该在 IE10+ 中工作,但它对我来说不起作用,只需单击链接(浏览器不执行任何操作,没有错误)...只有当我右键单击并将目标另存为“file.csv”时导航到该文件并双击它我可以打开该文件吗?

在此 JSFiddle 中测试两种方法(btoa/Blob)。 (这是代码)

<!doctype html>
<html>
<head>
</head>
<body>
  <a id="a" target="_blank">Download CSV (via btoa)</a>
  <script>
    var csv = "a,b,c\n1,2,3\n";
    var a = document.getElementById("a");
    a.href = "data:text/csv;base64," + btoa(csv);
  </script>
  <hr/>
  <a id="a2" download="Download.csv" type="text/csv">Download CSV (via Blob)</a>
  <script>
    var csv = "a,b,c\n1,2,3\n";
    var data = new Blob([csv]);
    var a2 = document.getElementById("a2");
    a2.href = URL.createObjectURL(data);
  </script>
</body>
</html>

原答案

我认为没有可用的选项。

我会调整您的代码,以便如果在用户系统上检测到 Flash 10+(截至 2009 年 9 月饱和度为 93%),请提供 Downloadify 选项,否则回退到服务器端请求。


3
投票
据我所知,这是不可能的:这就是创建 Downloadify 的原因。

您可以尝试链接到包含 CSV 数据的

data:URL

,但会出现跨浏览器问题。 
    


3
投票
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; }

我在其他地方找到了这段代码,

这里,以前


2
投票
如果您的用户拥有最新的浏览器,新的 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";
    

2
投票
HTML:

<a href="javascript:onDownload();">Download</a>

JavaScript:

function onDownload() { document.location = 'data:Application/octet-stream,' + encodeURIComponent(dataToDownload); }

摘自

如何从 JavaScript 将数据下载为文件


2
投票
我遇到过的最全面的解决方案是使用

FileSaver.js,通过后备方案为您处理许多潜在的跨浏览器问题。

它像其他海报一样利用了

Blob

 对象,创建者甚至创建了一个 
Blob.js polyfill,以防您需要支持不支持 Blob
 的浏览器版本
    

© www.soinside.com 2019 - 2024. All rights reserved.