Javascript Add New Rows To CSV (Append Prepend Insert)

Welcome to a tutorial on how to append, prepend, and insert new rows into an existing CSV file in Javascript. Yes, you read that right. This is modifying a CSV file directly in client-side Javascript, no need to upload the CSV file to the server.

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Click here to download. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

JAVASCRIPT CSV ADD NEW ROWS

All right, let us now get into the example of adding new rows to an existing CSV file in Javascript.

 

PART 1) THE HTML

1-csv-add.html
<!-- (A) JAVASCRIPT -->
<script src="csv.min.js"></script>
<script src="2-csv-add.js"></script> 

<!-- (B) FILE PICKER -->
<input type="file" accept=".csv" id="demo">
  1. We will be using this super simple CSV parser to read the CSV file.
  2. Captain Obvious at your service, a file picker that only accepts CSV files.

 

 

PART 2) THE JAVASCRIPT

2-csv-add.js
window.addEventListener("DOMContentLoaded", () => {
  // (A) FILE PICKER
  const picker = document.getElementById("demo");

  // (B) READ SELECTED CSV FILE
  picker.onchange = () => {
    let reader = new FileReader();
    reader.addEventListener("loadend", () => {
      // (B1) PARSE INTO ARRAY
      let data = CSV.parse(reader.result);

      // (B2) ADD NEW ROWS
      data.push(["A", "B"]); // APPEND
      data.unshift(["C", "D"]); // PREPEND
      data.splice(4, 0, ["E", "F"]); // INSERT

      // (B3) INSERT BEFORE "JOE DOE"
      let at = 0;
      for (let [i,r] of Object.entries(data)) {
        if (r.includes("Joe Doe")) { at =i; break; }
      }
      data.splice(at, 0, ["G", "H"]);

      // (B4) "CLEAN" CSV DATA
      // credit : https://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side
      data = data.map(row => row
        .map(String) // convert to string
        .map(v => v.replaceAll('"', '""')) // escape double quotes
        .map(v => `"${v}"`) // quote
        .join(",") // comma-separated
      ).join("\r\n"); // new line

      // (B5) FORCE DOWNLOAD
      var blob = new Blob([data], { type: "text/csv;charset=utf-8;" }),
          url = URL.createObjectURL(blob),
          a = document.createElement("a");
      a.href = url;
      a.setAttribute("download", "updated.csv");
      a.click();
      URL.revokeObjectURL(url);
      a.remove();
      picker.value = "";
    });
    reader.readAsText(picker.files[0]);
  };
});

This may look a little intimidating, but keep calm and study closely.

  • (A) On window load, get the file picker – picker = <input id="demo">.
  • (B) Read the CSV file that the user has picked –
    • reader = new FileReader()
    • reader.addEventListener("loadend", () => {...}
    • reader.readAsText(picker.files[0])
  • (B1) Parse the CSV file as an array using the CSV library – data = CSV.parse(reader.result)
  • (B2 & B3) Now that the CSV file is in an array, adding new rows is as simple as “usual array yoga”:
    • Use push to append to the end – data.push([...])
    • Use unshift to prepend to the start  – data.unshift([...])
    • Use splice to insert at an exact row – data.splice(ROW, 0, [...])
  • (B4) To convert the array back into a “CSV string”.
  • (B5) To force download the updated CSV, create an <a href="CSV-DATA" download="updated.csv"> and click on it.

 

 

EXTRA) FETCH CSV FROM URL

CSV.fetch({ url : "3-demo.csv" })
.done(data => {
  console.log(data);
  // ...
});

For those who want to load a CSV file from your server, just use CSV library’s CSV.fetch() function.

 

EXTRAS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

NOTE – LIMITED SYSTEM RESOURCES

We are reading an entire CSV file into the memory. Most modern devices should have no issues dealing with large CSV files, but there is still a limit to system resources. You may want to modify the script to check the file size before proceeding to read it.

 

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!