将javascript对象排列为CSV

时间:2014-03-01 13:02:22

标签: javascript jquery csv

我有一个格式为javascript的对象,

obj= {name:"name", phone:"phone" , email:"email"}

我希望在点击按钮时将其下载为CSV文件。

var list = []
var saveids = function(){
   obj.forEach(function(userrecord){
      list.push([obj.name,obj.email,obj.phone]);
   });
   window.open("data:text/octet-stream;charset=utf-8," + escape(list));
}

UI部分

$('#saveids').click(function(){
    saveids();
}

这将打开一个新窗口,其中所有数据都在一个连续的行中。

我无法弄清楚如何将数据正确格式化为CSV以及如何使<a #saveids>生成下载文件链接。

2 个答案:

答案 0 :(得分:1)

要将列表下载为CVS,您只需执行以下操作:

var forEach = Array.prototype.forEach,
    list = [
      {id: 1, name: 'Luke', phone: '999 999 999'},
      {id: 2, name: 'Yoda', phone: '999 222 333'}
    ],
    clipboard = "id,name,phone\n";

forEach.call(list, function(item){
    clipboard += item.id + "," + item.name + "," + item.phone + "\n";
});

content = "data:text/csv," + encodeURIComponent(clipboard);
location.href = content;

打开开发人员工具&gt;控制台并运行此代码以查看其运行情况。

答案 1 :(得分:0)

以下代码段将获取对象数组并生成csv,对象键将为标题,其余为值,并自动下载:-

function convertObjectListToCSV(dataObjectList) {


    var replacer = (key, value) => value === null ? '' : value // handle null values

    var header = Object.keys(dataObjectList[0])

    let csv = dataObjectList.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))

    csv.unshift(header.join(',')); //headers will be first row

    csv = csv.join('\r\n');//next row distinguished by '\r\n' in CSV


    var fileName = 'yourCsvFile.csv';//later can be dynamic name 

    // downloading file procedure, by oneshubh
    var downloadLink = document.createElement("a");
    downloadLink.download = fileName;
    downloadLink.href = window.URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
    downloadLink.click();// we need to revoke URL later
    // downloading file procedure end
}

用法用法:-

convertObjectListToCSV([{name:"name", phone:"phone" , email:"email"},
{name:"name1", phone:"phone1" , email:"email1"}])

working code