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 β€’ Read time 4 min read
Learn how you can export HTML tables to excel in two different ways, with and without 3rd party libraries, using JavaScript.
  • twitter
  • facebook
JavaScript

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

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:

Copied to clipboard! Playground
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

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:

Copied to clipboard! Playground
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

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:

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

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:

Copied to clipboard! Playground
const downloadLink = document.querySelector(`[download="${fileName}"]`)

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

    ...
}
Only generate download link once
πŸ” 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:

Copied to clipboard!
npm i xlsx

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:

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

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:

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

    XLSX.writeFile(workbook, 'table.xls')
})

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.

πŸ” 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 JavaScriptinfo Remove ads

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
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.