简体   繁体   English

如何使用javascript将内容添加到csv中的特定列?

[英]How to add content to specific column in csv using javascript?

I'm not good at javascript I've tried to search on stackoverflow.com but unable to find any help I'm trying to create CSV where I want to add content below relevant column heading/index, where the column heading/index is array key and column content is value, below is code but it is showing data only in two columns:我不擅长 javascript 我试图在 stackoverflow.com 上搜索,但找不到任何帮助我正在尝试创建 CSV,我想在相关列标题/索引下方添加内容,列标题/索引是数组键和列内容是值,下面是代码,但它仅在两列中显示数据:

 function downloadCSV(csvStr) {
  CSV = ConvertToCSV(csvStr);
  var uri = [
  [
    'application.csv','data:text/csv;charset=utf-8,' + escape(CSV)
  ]];
  downloadAll(uri)
}
function ConvertToCSV(objArray) {
   var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

   let str = "";
   for (var i = 0; i < array.length; i++) {
   var line = '';
   for (var index in array[i]) {
       if (line != '') line += ''
       line +=  `${index} ,` 
       line +=  `${array[i][index]}` 
      }
     str += line + '\n';
   }
   return str;
 }

And below is the array data I have where I want to use First, Street Address as the column heading下面是我想要使用的数组数据,首先,街道地址作为列标题

0: {First: 'asdkjf,\n', Street Address: 'lasdkfj ,\n', City: 
   'alsdf,\n', State: 'Alaska,\n', ZIP / Postal Code: 'asl;dfj,\n', …}
1: {First: 'asdkjf,\n', Street Address: 'lasdkfj ,\n', City: 'alsdf,\n', State: 'Alaska,\n', ZIP / Postal Code: 'asl;dfj,\n', …}

This is how I'm getting the result这就是我得到结果的方式在此处输入图像描述

Consider the following example.考虑以下示例。 This assumes you are receiving JSON Data format.这假设您正在接收 JSON 数据格式。

 var myDataArray = [{ "First": "asdkjf", "Street Address": "lasdkfj", "City": "alsdf", "State": "Alaska", "ZIP / Postal Code": "asl;dfj" }, { "First": "asdkjf", "Street Address": "lasdkfj", "City": "alsdf", "State": "Alaska", "ZIP / Postal Code": "asl;dfj" }]; function convertToCSV(jsonData) { var rows = []; jsonData.forEach(function(obj, i) { var keys = Object.keys(obj); keys.forEach(function(key, j) { rows.push(['"' + key + '"', '"' + obj[key] + '"'].join(",")); }); rows.push('\r\n'); }); return rows.join("\r\n"); } console.log(convertToCSV(myDataArray));

You can make use of many of the Array tools.您可以使用许多 Array 工具。 This helps create the comma separation.这有助于创建逗号分隔。 arr.join(",") will result in a String of each element of the array, joined by a , . arr.join(",")将生成数组中每个元素的字符串,由,连接。

This results in the following:这导致以下结果:

"First","asdkjf"\r\n
"Street Address","lasdkfj"\r\n
"City","alsdf"\r\n
"State","Alaska"\r\n
"ZIP / Postal Code","asl;dfj"\r\n
\r\n
"First","asdkjf"\r\n
"Street Address","lasdkfj"\r\n
"City","alsdf"\r\n
"State","Alaska"\r\b
"ZIP / Postal Code","asl;dfj"\r\n
\r\n

CSV Format is generally: CSV 格式一般为:

Cell1,Cell2,Cell3\r\n
Cell4,Cell5,Cell6\r\n

Where each line is terminated with a Carriage Return ( \r ) and New Line ( \n ) character at the End of Line.每行以回车符( \r )和换行符( \n )在行尾结束。 Some Operating systems do not use the Carriage Return.某些操作系统不使用回车。 If this is a Windows format, you will want to use both.如果这是 Windows 格式,您将需要同时使用这两种格式。 More complex CSV content may need to quoted, enclosed within double-quote characters.可能需要引用更复杂的 CSV 内容,并用双引号字符括起来。

See More:看更多:

Posting here because may be someone need it.在这里发帖是因为可能有人需要它。 I made some changes to the answer given by @Twisty because it was again creating only two columns where column one was heading( array key ) and two was content( array value ) what I needed was to add all headings ( array keys ) to top row and content ( array value ) to relevant box.我对@Twisty 给出的答案进行了一些更改,因为它再次只创建了两列,其中第一列是标题(数组键),第二列是内容(数组值)我需要将所有标题(数组键)添加到顶部行和内容(数组值)到相关框。 I know it's less efficient because I used three loops but it was the only choice to me so far!我知道它的效率较低,因为我使用了三个循环,但到目前为止它是我唯一的选择! Here is the code below:下面是代码:

function ConvertToCSV(objArray) {
    var jsonData = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var rows = [];
    let inc   = 1;
    jsonData.forEach(function(obj, i) {
    var keys = Object.keys(obj);
    let keyInc  = 1;
    if(inc === 1){
     keys.forEach(function(key, j) {
      if(keyInc === 1){
      rows.push([',"' + key + '"'].join(","));
     }else{
      rows.push(['"' + key + '"'].join(","));
    }
    keyInc++
  });
  rows.push('\n\n');
}
keys.forEach(function(key, j) {
  if(obj[key].includes('"')){
    let doubleQuoteValue = obj[key].replaceAll('"', '');
    rows.push(['"' + doubleQuoteValue + '"'].join(","));
    console.log('double quote',doubleQuoteValue);
  }else{
    rows.push(['"' + obj[key] + '"'].join(","));
  }
  console.log(obj[key]);
  
  keyInc++
});
 inc++;
 rows.push('\n');
});
return rows;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM