我使用本地浏览器内数据库来存储数据。但是,我想让用户能够将该数据导出为CSV。
谷歌搜索时我找到了带有数据网址的解决方案 - 用数据准备网址。然而,在我的情况下,每次呈现页面(链接)时生成的是> 1MB的数据。是否有任何替代解决方案可以让我从JavaScript生成文件下载,但不要求我提前准备内容 - 仅当用户实际点击链接时?
如果重要的是我使用React来构建我的应用程序..
答案 0 :(得分:13)
(不,不是那种)
var blob = new Blob(["CSV DATA HERE"], {type: "text/csv"});
var url = URL.createObjectURL(blob);
open(url);
(https://stackoverflow.com/a/14966131/6560716)
var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "";
data.forEach(function(infoArray, index){
dataString = infoArray.join(",");
csvContent += index < data.length ? dataString+ "\n" : dataString;
});
var blob = new Blob([csvContent], {type: "text/csv"});
var url = URL.createObjectURL(blob);
open(url);
var blob = new Blob(["CSV DATA HERE"], {type: "text/csv"});
var url = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "filename.csv");
document.body.appendChild(link);
link.click();
var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "";
data.forEach(function(infoArray, index){
dataString = infoArray.join(",");
csvContent += index < data.length ? dataString+ "\n" : dataString;
});
var blob = new Blob([csvContent], {type: "text/csv"});
var url = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "filename.csv");
document.body.appendChild(link);
link.click();