Monday, December 12, 2022

Create and Download Excel File in JavaScript


 


In this post we'll display a simple method to create Excel file from an HTML table, and download it.

First we create an HTML table based on our data:


function getHtmlTable() {
const data = [
['Name', 'Age', 'Height'],
['Alice', 56, 180],
['Bob', 47, 176]
]
const rows = data.map(row => {
const columns = row.map(column => {
return `<td>${column}</td>`
})
return `<tr>${columns.join('')}</tr>`
})
return `<table>${rows.join('')}</table>`
}


Next we create a download as an Excel file:


function exportToExcel() {
const htmlTable = getHtmlTable()
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(htmlTable))
}


Final Note


Notice that while this method is extremely simple, we cannot have control over the excel file styling, and the downloaded file name.
 



No comments:

Post a Comment