【问题标题】:Saving the result of a function with for-loop as csv file in JavaScript在 JavaScript 中将带有 for-loop 的函数的结果保存为 csv 文件
【发布时间】:2018-04-04 07:21:46
【问题描述】:

我在 Stack Overflow 和 Google 中搜索了很多,但不幸的是没有答案。

我用JS写了一段代码,它给了我这样一个“预期和正确”的结果:

W,52.xxxxx,10.1
W,52.xxxxx,10.2
W,52.xxxxx,10.3
W,52.yyyyy,10.1
W,52.yyyyy,10.2
W,52.yyyyy,10.3

问题是这样的行列表太大,我无法在Android中完全复制它,所以我想将此列表保存为csv文件,而不是通过命令将其显示在网页上

"document.write"

我在其他人的代码的帮助下修改了我的代码,但它不起作用。 我变成了“未定义”这个词,而不是 csv 文件中的数据列表:(

代码在这里:

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>

    </body>
    <script>
        function convertTo()
{

    var lon,lat;

    for(lat = 52 + (1/3600) ; lat <= 52 + (3/3600) ; lat=lat+(1/3600))

    {

       for(lon = 9 + (1/3600) ; lon<= 9 + (4/3600) ; lon=lon+(1/3600))
           {

      document.write("W,"+lat+","+lon+"<br>")

           }
    }

};

var CSV = convertTo();

window.URL = window.webkitURL || window.URL;

var contentType = 'text/csv';

var csvFile = new Blob([CSV], {type: contentType});

var a = document.createElement('a');

a.download = 'my.csv';

a.href = window.URL.createObjectURL(csvFile);

a.textContent = 'Download as CSV';

a.dataset.downloadurl = [contentType,

a.download, a.href].join(':');

document.body.appendChild(a);


    </script>
</html>

请帮忙!

提示:我是 JS 初学者

编辑: 在这里,我得到了导出到 csv 文件的代码,并用我的代码添加和修改:

Lee Kowalkowski's answer

【问题讨论】:

  • 第一个问题是你在文档上写尝试获取 CSV 变量,你应该使用变量而不是 document.write... 并使用 return
  • @Ferhat 所以我应该删除 document.write("W,"+lat+","+lon+"
    ") 然后写 return("W,"+lat+","+lon+ "
    ") ?!!
  • var lon, lat, str str+=......函数结束返回str

标签: javascript csv copy export export-to-csv


【解决方案1】:

您好,很抱歉,您可以在jsfiddle 中使用下面的代码也可以使用代码

脚本

function convertTo()
{
var lon,lat;
var str ='';
for(lat = 52 + (1/3600) ; lat <= 52 + (3/3600) ; lat=lat+(1/3600))
{
   for(lon = 9 + (1/3600) ; lon<= 9 + (4/3600) ; lon=lon+(1/3600))
       {
  str+="W;"+lat+";"+lon+"\n";
       }
}
return str;
};
var CSV = convertTo();
window.URL = window.webkitURL || window.URL;
var contentType = 'text/csv';
var csvFile = new Blob([CSV], {type: contentType});
var a = document.createElement('a');
a.download = 'my.csv';
a.href = window.URL.createObjectURL(csvFile);
a.textContent = 'Download as CSV';
a.dataset.downloadurl = [contentType,
a.download, a.href].join(':');
document.body.appendChild(a);

【讨论】:

  • 非常感谢,您能帮帮我吗?!!我修改了我的代码,以便我可以直接在 html 中输入我的值,但是代码不起作用!!!为什么?!!全局变量必须从函数中读取!!请有我的代码:jsfiddle.net/4473vjbw
  • 这个“确认”按钮是可选的,我放它只是为了检查输入的值
  • 是的,但我现在不在,你可以在我有空的时候问你的问题,然后可以帮助你
  • 谢谢,如果我将我的问题作为新问题发布会更好吗?!
  • 不,作为新问题提出不是必需的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2019-03-25
  • 2019-06-21
相关资源
最近更新 更多