使用 javascript 将文件下载为 .csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17564103/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:47:36  来源:igfitidea点击:

Using javascript to download file as a.csv file

javascriptcsv

提问by Samuel Tang

Hi I am trying to export a file as .csv file, so that when the user clicks on the download button, the browser would automatically download the file as .csv. I also want to be able to set a name for the .csv file to be exported

嗨,我正在尝试将文件导出为 .csv 文件,以便当用户单击下载按钮时,浏览器会自动将文件下载为 .csv。我还希望能够为要导出的 .csv 文件设置名称

I am using javascript to do this

我正在使用 javascript 来做到这一点

Code is below:

代码如下:

 function ConvertToCSV(objArray) {
            var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
            var str = '';

            for (var i = 0; i < array.length; i++) {
                var line = '';
            for (var index in array[i]) {
                if (line != '') line += ','

                line += array[i][index];
            }

            str += line + '\r\n';
        }

        return str;
    }

    // Example
    $(document).ready(function () {

        // Create Object
        var items = [
              { "name": "Item 1", "color": "Green", "size": "X-Large" },
              { "name": "Item 2", "color": "Green", "size": "X-Large" },
              { "name": "Item 3", "color": "Green", "size": "X-Large" }];

        // Convert Object to JSON
        var jsonObject = JSON.stringify(items);

        // Display JSON
        $('#json').text(jsonObject);

        // Convert JSON to CSV & Display CSV
        $('#csv').text(ConvertToCSV(jsonObject));

        $("#download").click(function() {
            alert("2");
            var csv = ConvertToCSV(jsonObject);
            window.open("data:text/csv;charset=utf-8," + escape(csv))
            ///////


        });

    });

Please advise on this My Boss is breathing down my neck on this issue

请就此提出建议 我的老板在这个问题上对我不屑一顾

Please help

请帮忙

回答by Jewel

I have written a solution in this thread: how to set a file name using window.open

我在此线程中编写了一个解决方案:如何使用 window.open 设置文件名

This is the simple solution:

这是简单的解决方案:

 $("#download_1").click(function() {
var json_pre = '[{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]';
var json = $.parseJSON(json_pre);

var csv = JSON2CSV(json);
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csv]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "data.csv";

document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});

JSON2CSV function

JSON2CSV 函数

function JSON2CSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
    var line = '';

    if ($("#labels").is(':checked')) {
        var head = array[0];
        if ($("#quote").is(':checked')) {
            for (var index in array[0]) {
                var value = index + "";
                line += '"' + value.replace(/"/g, '""') + '",';
            }
        } else {
            for (var index in array[0]) {
                line += index + ',';
            }
        }

        line = line.slice(0, -1);
        str += line + '\r\n';
    }

    for (var i = 0; i < array.length; i++) {
        var line = '';

        if ($("#quote").is(':checked')) {
            for (var index in array[i]) {
                var value = array[i][index] + "";
                line += '"' + value.replace(/"/g, '""') + '",';
            }
        } else {
            for (var index in array[i]) {
                line += array[i][index] + ',';
            }
        }

        line = line.slice(0, -1);
        str += line + '\r\n';
    }
    return str;
}

回答by cocco

in modern browsers there is a new attribute in anchors.

在现代浏览器中,anchors 中有一个新属性。

download

download

http://caniuse.com/download

http://caniuse.com/download

so instead of using

所以而不是使用

window.open("data:text/csv;charset=utf-8," + escape(csv))

create a download link:

创建下载链接:

<a href="data:text/csv;charset=utf-8,'+escape(csv)+'" download="filename.csv">download</a>

another solution is to use php

另一个解决方案是使用 php

EDIT

编辑

i don't use jQuery, but you need to edit your code to add the download link with something like that in your function.

我不使用 jQuery,但您需要编辑代码以在函数中添加类似内容的下载链接。

var csv=ConvertToCSV(jsonObject),
a=document.createElement('a');
a.textContent='download';
a.download="myFileName.csv";
a.href='data:text/csv;charset=utf-8,'+escape(csv);
document.body.appendChild(a);

回答by user1274820

I just wanted to add some code here for people in the future since I was trying to export JSON to a CSV document and download it.

我只是想在这里为将来的人们添加一些代码,因为我试图将 JSON 导出到 CSV 文档并下载它。

I use $.getJSONto pull json data from an external page, but if you have a basic array, you can just use that.

$.getJSON过去常常从外部页面中提取 json 数据,但是如果您有一个基本数组,则可以使用它。

This uses Christian Landgren'scode to create the csv data.

这使用Christian Landgren 的代码来创建 csv 数据。

$(document).ready(function() {
    var JSONData = $.getJSON("GetJsonData.php", function(data) {
        var items = data;
        const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
        const header = Object.keys(items[0]);
        let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
        csv.unshift(header.join(','));
        csv = csv.join('\r\n');

        //Download the file as CSV
        var downloadLink = document.createElement("a");
        var blob = new Blob(["\ufeff", csv]);
        var url = URL.createObjectURL(blob);
        downloadLink.href = url;
        downloadLink.download = "DataDump.csv";  //Name the file here
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
    });
});

Edit: It's worth noting that JSON.stringifywill escape quotes in quotes by adding \". If you view the CSV in excel, it doesn't like that as an escape character.

编辑:值得注意的是,JSON.stringify将通过添加\". 如果您在 excel 中查看 CSV,它不喜欢将其作为转义字符。

You can add .replace(/\\"/g, '""')to the end of JSON.stringify(row[fieldName], replacer)to display this properly in excel (this will replace \"with ""which is what excel prefers).

您可以添加.replace(/\\"/g, '""')到年底JSON.stringify(row[fieldName], replacer)在Excel这个正常显示(这将取代\"""这是Excel中喜欢什么)。

Full Line: JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""')

全线: JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""')

回答by YouBee

Try these Examples:

试试这些例子:

Example 1:

示例 1:

JsonArray = [{
    "AccountNumber": "1234",
    "AccountName": "abc",
    "port": "All",
    "source": "sg-a78c04f8"

}, {
    "Account Number": "1234",
    "Account Name": "abc",
    "port": 22,
    "source": "0.0.0.0/0",
}]

JsonFields = ["Account Number","Account Name","port","source"]

function JsonToCSV(){
    var csvStr = JsonFields.join(",") + "\n";

    JsonArray.forEach(element => {
        AccountNumber = element.AccountNumber;
        AccountName   = element.AccountName;
        port          = element.port
        source        = element.source

        csvStr += AccountNumber + ',' + AccountName + ','  + port + ',' + source + "\n";
        })
        return csvStr;
}

You can download the csv file using the following code :

您可以使用以下代码下载 csv 文件:

function downloadCSV(csvStr) {

    var hiddenElement = document.createElement('a');
    hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvStr);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'output.csv';
    hiddenElement.click();
}

回答by paulo carraca

If your data comes from a SQL Database, all your lines should have the same structure, but if coming from a NoSQL Database you could have trouble using standard answers. I elaborated on above JSON2CSV for such a scenario. Json data example

如果您的数据来自 SQL 数据库,则所有行都应该具有相同的结构,但如果来自 NoSQL 数据库,您可能无法使用标准答案。我在上面的 JSON2CSV 中详细说明了这种情况。Json 数据示例

  [ {"meal":2387,"food":"beaf"},
    {"meal":2387,"food":"apple","peeled":"yes", "speed":"fast" },
    {"meal":2387,"food":"pear", "speed":"slow", "peeled":"yes" } ]

Answer

回答

"meal","food","peeled","speed"
"2387","beaf","",""
"2387","apple","yes","fast"
"2387","pear","yes","slow"

Code for headers and double quotes for simplicity.

为简单起见,标题和双引号的代码。

function JSON2CSV(objArray) {
  var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

  var str = '';
  var line = '';

  // get all distinct keys      
  let titles = [];
  for (var i = 0; i < array.length; i++) {
    let obj = array[i];
    Object.entries(obj).forEach(([key,value])=>{
      //console.log('key=', key, "   val=", value );
      if (titles.includes(key) ) {
        // console.log (key , 'exists');
        null;
      }
      else {
        titles.push(key);
      }
    })
  }
  let htext =  '"' + titles.join('","') + '"';
  console.log('header:', htext);
  // add to str
  str += htext + '\r\n';
  //
  // lines
  for (var i = 0; i < array.length; i++) {
    var line = '';
    // get values by header order
    for (var j = 0; j < titles.length; j++) {
      // match keys with current header
      let obj = array[i];
      let keyfound = 0;    
      // each key/value pair
      Object.entries(obj).forEach(([key,value])=>{
        if (key == titles[j]) {
          // console.log('equal tit=', titles[j] , ' e key ', key ); // matched key with header
          line += ',"' + value +  '"';
          keyfound = 1; 
          return false;
        }

      })
      if (keyfound == 0) {
        line += ',"'  +  '"';   // add null value for this key
      } // end loop of header values

    }

    str += line.slice(1) + '\r\n';
  }
  return str;
}