2 Easy Ways to Export HTML Tables to Excel

2 Easy Ways to Export HTML Tables to Excel

With and without 3rd party libraries
Ferenc Almasi β€’ 2023 July 18 β€’ πŸ“– 4 min read

Using HTML tables is a great way to represent data in a structured format. For applications working with lots of tables, you may come across the need to export them for later use. The most viable solution, in this case, is to store the data in a spreadsheet.

In this tutorial, we'll take a look at how to export HTML tables to Excel in two different ways. Click on the button below to test its functionality and export the table below.

TechProperties
HTMLCreate hyperlinked documents
CSSDesign beautiful websites
JSAdd interactivity to your apps
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Export Table using Vanilla JavaScript

To export HTML tables to Excel using vanilla JavaScript, we need a button as well as a click event listener attached to the button that will trigger the export. Create a button with the id of download in your HTML file and add the following JavaScript code:

const onClick = (selector, callback) => {
    const element = document.querySelector(selector)

    element.addEventListener('click', callback)
}

// Download with Vanilla JS
onClick('#download', () => { ... })
Add click event listener to button
Copied to clipboard!

If you don't already have one, create a utility function for click events called onClick. We'll reuse it for the other example. To trigger the export, add the following code to the callback:

onClick('#download', () => {
    const dataType = 'application/vnd.ms-excel'
    const tableSelect = document.querySelector('table')
    const tableHTML = tableSelect.outerHTML.replace(/ /g, '%20')
    const downloadLink = document.createElement('a')
    const fileName = 'table.xls'
    
    document.body.appendChild(downloadLink)
    
    downloadLink.href = `data:${dataType}, ${tableHTML}`
    downloadLink.download = fileName
    downloadLink.click()
})
Export HTML table to Excel
Copied to clipboard!

This works by creating an anchor on the page with a download attribute. When the download attribute is present, it will trigger a download instead of navigation. We can use a data URL to generate the contents of the Excel file. It needs to have the following syntax:

data:application/vnd.ms-excel, <table>...</table>
Copied to clipboard!

Data URLs always start with data: followed by the MIME type. In our case, it isΒ application/vnd.ms-excel. This needs to be followed by the table itself.

Note that spaces need to be URL encoded asΒ %20 to ensure proper display.

However, with this solution, a new link is created every time the button is clicked. This means that each time you click the button, the data URL is regenerated as well with all of the table's data.

This may not be a problem for smaller tables, but if you're concerned about performance, we can add a check to only generate the download link if it hasn't been generated yet. To achieve this, we can modify the above script as follows:

const downloadLink = document.querySelector(`[download="${fileName}"]`)

if (downloadLink) {
    downloadLink.click()
} else {
    const downloadLink = document.createElement('a')

    ...
}
Only generate download link once
Copied to clipboard!
πŸ” Become a member or login to get access to the full source code in one piece.

Export Table using SheetJS

Another approach to exporting HTML tables to spreadsheets is to use SheetJS. SheetJS is an all-in-one spreadsheet data parser and writer. To add SheetJS to your project, run the following command in your terminal:

npm i xlsx
Copied to clipboard!

Otherwise, you can also include the bundled version of the script from SheetJS's official CDN. If you don't have an NPM project, import the library using the following script tag:

<script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>
Copied to clipboard!

To achieve the same behavior as before, we need to call utils.table_to_book on the library, then export the created workbook using the writeFile method:

onClick('#download', () => {
    const table = document.querySelector('table')
    const workbook = XLSX.utils.table_to_book(table, { sheet: 'table' })

    XLSX.writeFile(workbook, 'table.xls')
})
Copied to clipboard!

We need to pass the table DOM element to table_to_book. It also accepts a configuration object where we can name the spreadsheet using the sheet property. The writeFile method expects this workbook as the first parameter and the name of the file as the second.

πŸ” Become a member or login to get access to the full source code in one piece.
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Conclusion

In conclusion, exporting HTML tables to Excel can be done in about 20 lines of code without any library. If you also need to read XLS or perform other transformations with Excel files, it is recommended to use SheetJS instead. On the other hand, use the first solution if you're concerned about bundle size and only need the export functionality.

Is there anything you think this tutorial is missing? Let us know in the comments below! If you would like to learn more about JavaScript, make sure you check out our roadmap below. Thank you for reading, happy coding!Β πŸ‘¨β€πŸ’»

Master JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended