Looking for an efficient way to export array data to an Excel format using JavaScript? You’ve come to the right place! With our two easy-to-use solutions, you can quickly convert your array data into either an Excel or CSV format.
In Solution 1, we start by filtering out any duplicate items from the two arrays and then merging the resulting array. We then use the JSON.stringify method to convert the array data into a JSON string before creating a Blob and downloading it as an Excel file using the FileSaver.js library. It’s that simple!
In Solution 2, we use a nested forEach loop to extract each item from the two arrays and generate a CSV string accordingly. We then create a link element and use the data URI scheme to download the resulting CSV file without using any external library.
How to Export Array to Excel using JavaScript
In HTML, create two button elements and call exportToCsv() and exportToExcel() function onclcik event attribute. The HTML code is optional, you can run the function programtically according to your needs.
<button onclick="exportToCsv()">export to CSV</button> <button onclick="exportToExcel()">export to Excel</button>
Now, load the FileSaver JS by adding the following CDN link before closing the body tag.
<script src='https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js'></script>
Define your data inside the array and initialize the function by adding the following JavaScript function to your project.
// Solution 1 var array1 = ["Item 1", "Item 3"]; var array2 = ["Item 2", "Item 4"]; let noDuplicate = array1.filter(i => array2.findIndex(a => i == a) == -1); let result = [...noDuplicate, ...array2]; console.log(result); exportToExcel = function() { console.profile('Methods Start'); var myJsonString = JSON.stringify(result); var blob = new Blob([myJsonString], { type: "application/vnd.ms-excel;charset=utf-8" }); saveAs(blob, "Report.xls"); console.profileEnd(); // 4903.267ms }; // Solution 2, Without FileSaver.js var Results = [array1, array2]; exportToCsv = function() { var CsvString = ""; Results.forEach(function(RowItem, RowIndex) { RowItem.forEach(function(ColItem, ColIndex) { CsvString += ColItem + ","; }); CsvString += "\r\n"; }); CsvString = "data:application/csv," + encodeURIComponent(CsvString); var x = document.createElement("A"); x.setAttribute("href", CsvString); x.setAttribute("download", "somedata.csv"); document.body.appendChild(x); x.click(); };
That’s all! hopefully, you have successfully created a feature to export array to Excel using JavaScript. If you have any questions or suggestions, feel free to comment below.