Welcome folks today in this blog post we will be using the xlsx.js
library to export all sheets
of excel
file and download it as csv
file in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
and include the below code as shown below
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<!DOCTYPE html> <html> <head> <title>Excel to CSV Converter</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.1/xlsx.full.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <div class="form-group"> <input type="file" class="form-control" required id="fileInput" accept=".xlsx"> </div> <table class="table table-striped" id="sheetTable"></table> </div> <script> // get file input element const fileInput = document.getElementById('fileInput'); // add event listener to file input fileInput.addEventListener('change', function(e) { const file = e.target.files[0]; // read file with FileReader const reader = new FileReader(); reader.onload = function() { const data = new Uint8Array(this.result); const workbook = XLSX.read(data, {type: 'array'}); // create table header const table = document.getElementById('sheetTable'); const header = table.createTHead().insertRow(); header.insertCell().appendChild(document.createTextNode('Sheet Name')); header.insertCell().appendChild(document.createTextNode('Download')); // create table rows for each sheet workbook.SheetNames.forEach(function(sheetName) { const row = table.insertRow(); row.insertCell().appendChild(document.createTextNode(sheetName)); const downloadButton = document.createElement('button'); downloadButton.textContent = 'Download'; downloadButton.addEventListener('click', function() { // convert sheet to CSV and download const csv = XLSX.utils.sheet_to_csv(workbook.Sheets[sheetName]); const blob = new Blob([csv], {type: 'text/csv;charset=utf-8;'}); const link = document.createElement('a'); link.download = sheetName + '.csv'; link.href = URL.createObjectURL(blob); link.click(); }); row.insertCell().appendChild(downloadButton); }); }; reader.readAsArrayBuffer(file); }); </script> </body> </html> |