在将数据下载为CSV文件之前如何格式化数据?

时间:2019-01-10 18:05:41

标签: javascript reactjs csv ecmascript-6 filesaver.js

我正在尝试以CSV格式下载一些数据,但是我正在文件中获取此数据:

  

[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象]

我正在使用file-saver

这就是我的做法:

  const downloadFile = () => {

    const formatCSVData = shipmentsCSV.shipments.map(data => ({
      Courier: data.courierName,
      Status: data.status.name,
    }));

    console.log('formatCSVData', JSON.stringify(formatCSVData, null, 2));

    const blob = new Blob([formatCSVData], {
      type: 'text/csv;charset=UTF-8',
    });

    saveAs(blob, 'CSV.txt');
  };

第二个console.log记录了此内容(26个项目,但我将简化为4个项目):

[
  {
    "Courier Name": "Hand Delivery",
    "Status": "Received"
  },
  {
    "Courier Name": null,
    "Status": "Pending"
  },
  {
    "Courier Name": null,
    "Status": "Canceled"
  },
  {
    "Courier Name": "FedEx",
    "Status": "Canceled"
  }
  ...
]

那么,如何正确在CSV文件上打印数据?

1 个答案:

答案 0 :(得分:0)

尝试以下解决方案:

How to convert JSON to CSV format and store in a variable

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;
        }

您的代码将是:

const downloadFile = () => {

    const shipments = shipmentsCSV.shipments.map(data => ({
      Courier: data.courierName,
      Status: data.status.name,
    }));

    const formatCSVData = ConvertToCSV(shipments);
    console.log('formatCSVData', JSON.stringify(formatCSVData, null, 2));

    const blob = new Blob([formatCSVData], {
      type: 'text/csv;charset=UTF-8',
    });

    saveAs(blob, 'CSV.txt');
  };