0

I would like to know if there is a way to export data from a CSV file to a javascript object and when someone edits the CSV file it automatically changes in the javascript file. Thank you so much.

2
  • 1
    do you want to import csv file ? Commented Nov 6, 2019 at 10:14
  • @Narayanan I want to take data from a csv file and put it on an object for example I have this: ` data: [ { x:'01.08.2018', y: 0 },{ x:'03.08.2018', y: -0.16 }, ` and i want to change the value for the data of a csv file Commented Nov 6, 2019 at 10:18

1 Answer 1

1

The following steps are implemented in the below code snippet.Customize this as required.

  1. Select input CSV file. (The code snippet is tested for UTF-8 encoded CSV file)
  2. Read the CSV file data
  3. Parse the CSV file data and contruct the JSON object
  4. Manipulate or modify the JSON object if required.
  5. Export the JSON object as CSV

var CsvRows;
var headers;

// This event will be triggered when file is selected
// Note: This code is tested for UTF-8 encoded CSV file 
function handleChange(evt) {
  var reader = new FileReader();
  reader.onload = function() {
  
    //reader.result gives the file content
    document.getElementById('out').innerHTML = reader.result;
    
    //parse the result into javascript object
    var lines = reader.result.split('\r\n');
    headers = lines[0].split(',');
    lines.shift();
    CsvRows = lines.map((item) => {
      var values = item.split(',');
      var row = {};
      headers.map((h, i) => {
        row[h] = values[i];
      });
      return row;
    });
    console.log(CsvRows);
    document.getElementById('result').style.display = 'block'
  };

  //read the selected file
  reader.readAsBinaryString(evt.files[0]);
};


//export the javscript object as csv
function exportCSV() {
  //contruct the csv ad data url
  let csvContent = "data:text/csv;charset=utf-8," +
    headers.join(",") + "\r\n";


  //contruct the data in csv format
  var data = CsvRows.map(e => {
    var line = '';
    headers.map((h) => {
      line += e[h] + ',';
    });
    return line.substr(0, line.length - 1);
  }).join("\r\n")

  csvContent += data;

  //contruct an anchor tag 
  var encodedUri = encodeURI(csvContent);
  var link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  
  //provide the export file name
  link.setAttribute("download", "mydata.csv");
  document.body.appendChild(link); // Required for FF

  //trigger download of CSV
  link.click();

  link.remove();
}
<input type="file" onchange="handleChange(this)" accept=".csv" />

<div id="result" style="display:none;">
  <div id="out"></div>
  <div>See console for Javascript Object.</div>
  <div>Export the imported file <button onclick="exportCSV()">Export</button></div>
</div>

The above code snippet only works for CSV files. Custom implementation has to be made for Excel files.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.