简体   繁体   中英

Export html table to csv in Javascript

I have two functions

Exports HTML Table Download CSV file

function exportTableToCSV(filename) {
    var csv = [];
    var rows = document.querySelectorAll("table tr");

    for(var i = 0; i < rows.length; i++){
        var row = [], cols = rows[i].querySelectorAll("td, th");
        for(var j = 0; j < cols.length; j++){
            row.push(cols[j].innerText);
        }
        csv.push(row.join(","));
    }

    // download csv file
    downloadCSV(csv.join("\n"), filename);
}

function downloadCSV(csv, filename) {
        var csvFile;
    var downloadLink;

    csvFile = new Blob([csv], {type:"text/csv"});
    downloadLink = document.createElement("a");
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}

exportTableToCSV('test.csv');

I have a situation here this code works good where there is an array

[1,2] [3,4] [5,6]

but if the data is

[1,"example1,data1",10] [2,"example1,data2",20]

the csv file generates two extra columns for example1 and data 1. how do we make sure both "example1,data1" stays in one column. how to implement if there is a string with multiple commas in an array?

Thanks,

Swathi

//dataToBeDocumented= [{object},{object},{object}] should be this format

function ConvertToCSV(objArray) {
  var array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
  try {
    var str = "";
    var obj = array[0] ? array[0] : null;
    var res = Object.keys(obj);
  } catch (err) {
    return err;
  }

  res = res.join(",");
  // console.log(res);
  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";
  }
  // console.log(str);
  return res + "\r\n" + str;
}
function makeCSV(content, outputFileName) {
    this.content = content;
    if (typeof this.content === "string") {
      this.content = JSON.parse(this.content);
    }
    try {
      var uri = "data:text/csv;charset=utf-8," + ConvertToCSV(this.content);
    } catch (err) {
      throw err;
    }
    var downloadLink = document.createElement("a");
    downloadLink.href = uri;
    var opFileName = `${outputFileName}.csv`;
    // console.log(opFileName);
    downloadLink.download = opFileName;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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