Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

JavaScript Table to Excel: Export Guide

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The quickest reliable way to turn an HTML table into an Excel file in JavaScript is to build a workbook in the browser with a library like SheetJS (the xlsx package), then trigger a download. You read the table's cells with standard DOM methods, hand the data to the library, and let it produce a real .xlsx file. This works entirely client-side, needs no server, and preserves numbers and dates as Excel types rather than flattening everything into text. If you only need something a spreadsheet app will open, a CSV download written by hand is a lighter alternative, but it loses formatting and some type information. The steps below cover the proper workbook route, with notes on the CSV fallback.

What You'll Need

  • A working HTML page with a <table> element whose rows and cells are rendered in the DOM.
  • A JavaScript build setup or a plain script tag. SheetJS is distributed on npm and also as a standalone browser script you can include from a CDN or host yourself.
  • Basic comfort with document.querySelector, loops, and event listeners.
  • A modern browser for testing, and Excel, LibreOffice Calc, or Google Sheets to verify the downloaded file.
  • Optional: a date-handling library if your table contains dates you want Excel to treat as real dates rather than text.

Step-by-Step

  1. Add the library. If you use a bundler, install the xlsx package from npm and import it. If you are on a plain page, add a script tag pointing at the standalone build, served from the official project distribution or a CDN you trust. Do not download random copies from file-sharing sites; always use the official package or its documented CDN URL.
  2. Give the table a stable handle. Add an id to the table, for example <table id="report-table">. This removes any ambiguity when the page has several tables and makes your selector readable.
  3. Read the rows and cells. Select the table with document.getElementById('report-table'), then iterate its rows collection. For each row, iterate row.cells and read cell.innerText or cell.textContent. Use innerText when you want the visible text (hidden cells excluded), and textContent when you want everything in the markup. Build a two-dimensional array, one inner array per row.
  4. Decide which rows to skip. If your table has a header row, keep it and pass it as the header. If you have footer rows with totals, either include them deliberately or slice them off with rows.length - 1. Check for rows hidden with CSS or collapsed groups, because they will still appear in the rows collection unless you filter them out.
  5. Handle the header separately. Take the first row's cell texts as an array of column names. Libraries like SheetJS accept a header array, or you can write the header as the first data row and set the sheet's range to start below it. Keeping the header explicit means the Excel column letters align with your data correctly.
  6. Preserve numbers where it matters. A value read as "1200" from the DOM becomes text in the workbook unless you convert it. For numeric columns, strip currency symbols and thousands separators, then pass a real number. Convert carefully: a leading zero (like a product code 007) should stay text, and very large IDs (order numbers) should stay text so Excel does not show them in scientific notation.
  7. Insert the data into a worksheet. With SheetJS, XLSX.utils.aoa_to_sheet converts your array of arrays into a worksheet object. Pass an option to skip the header row if you supplied one separately. If your data is an array of objects, XLSX.utils.json_to_sheet is often cleaner and uses the object keys as column headers.
  8. Widen columns so the file opens legibly. Set column widths on the worksheet object, for example an array of { wch: 20 } style objects mapped to the columns. Without this, Excel opens with narrow columns showing #### or truncated text, which looks broken to whoever downloads the file.
  9. Create the workbook and append the sheet. Build a new workbook with XLSX.utils.book_new(), then attach the sheet with XLSX.utils.book_append_sheet(workbook, worksheet, 'Report'). The sheet name is limited to 31 characters and cannot contain characters Excel forbids, such as :, \, /, ?, *, [ or ].
  10. Write the file out. With SheetJS in the browser, call XLSX.writeFile(workbook, 'report.xlsx'). This produces the file and starts the download in one call. If you need more control over the filename or download timing, use XLSX.write to get the binary data and wrap it in a Blob, then create an object URL and click a temporary anchor element.
  11. Wire it to a button. Add a button with an event listener that runs the export function. Disable the button while the export runs if the table is large, and re-enable it in a finally block so a failure does not leave it stuck.
  12. Verify the output. Open the downloaded file in a real spreadsheet app. Check the header row, that numbers are right-aligned (a sign they are stored as numbers), that dates display as dates, and that long text is not lost. Re-open it after saving to confirm Excel does not warn about a corrupt file.
  13. Consider the CSV fallback. If you only need raw data, build the CSV string yourself, quote fields that contain commas, quotes or line breaks, escape inner quotes by doubling them, prefix a byte order mark so Excel reads UTF-8 correctly, and download it as a Blob. CSV cannot carry formatting, multiple sheets, or reliable types.

Common Mistakes

The most frequent error is treating exported numbers as text, which breaks sums and sorting in the spreadsheet. Next is an off-by-one on the header: either the header ends up duplicated as a data row, or the first data row is lost. Another common slip is using innerHTML instead of innerText, so cells containing markup or entities arrive with tags or encoded characters inside them. Many exports also drop hidden rows without noticing, or include them without intending to. Filename collisions matter too: always set a .xlsx extension, because a file without it will not open by double-click. A subtler issue is generating the export from a table that has been re-rendered by a framework but whose underlying data lives in state; read from the source data, not the DOM, if the DOM is virtualised. Finally, people forget that dates scraped from the DOM are strings, so Excel will not sort them chronologically.

Tips

Export from your data model rather than the DOM whenever possible: it is faster, immune to hidden rows and pagination, and keeps types clean. If the table is paginated, export the whole dataset, not the visible page. For big tables, build the array with a single pass and avoid repeated DOM queries inside loops. Store a timestamp in the filename so repeat downloads do not overwrite each other. Test with awkward data: empty cells, values containing commas and quotes, negative numbers, currency symbols, and non-Latin characters. If the file is for a specific team, freeze the header row and give the columns sensible widths so it opens ready to read. Keep the export logic in one function so a second table can reuse it.

Troubleshooting

If nothing downloads, check the browser console first: a thrown error stops the function before the write call. Confirm the library loaded by logging it, and confirm your table selector returned an element rather than null (a common cause is running the script before the table exists, so move it below the table or wait for the DOM). If the file downloads but Excel refuses to open it, you may be writing a string to a .xlsx filename; check you used the workbook writer, not a text writer. If numbers appear as text, inspect how you read the cells and convert explicitly. If characters look garbled, ensure the page and export both use UTF-8. If the download is blocked, some browsers block programmatic clicks not triggered by a user action, so call the export directly from the button handler. If the browser hangs on very large tables, split the export into chunks or keep it to the data model.

Frequently Asked Questions

Do I need a server to export a table to Excel?

No. The workbook can be built and downloaded entirely in the browser. A server is only useful for very large datasets or for generating files on a schedule.

Can I export multiple tables into one file?

Yes. Create one worksheet per table and append each to the same workbook, giving each sheet a unique name of 31 characters or fewer.

Why do my numbers show as text in Excel?

Because they were read from the DOM as strings. Convert them to numbers before writing, but keep identifiers with leading zeros as text.

Does CSV work instead of XLSX?

For plain data, yes, and it is simpler. It cannot store formatting, multiple sheets, or strict types, and you must handle quoting and encoding yourself.

Can I keep cell colours and merged cells?

Merged cells and some styling can be written, but it is more involved than exporting values. If the source table uses complex CSS, expect to recreate styling in the workbook rather than copying it automatically.