How to Export HTML Table to CSV: A Practical Guide
By the LightCube Data team ยท Updated 2026-11-27
Knowing how to export HTML table to CSV is mostly a matter of reading the table rows in the browser, converting each cell into a valid CSV value, and downloading the result as a text/csv file. Plain JavaScript can do this without a server, and the same output opens cleanly in Excel, Google Sheets, or any CSV viewer.
TL;DR: - A CSV file is plain text: one line per table row, cells separated by commas, with special characters escaped. - Plain JavaScript can read the rows, build the CSV string, and download it with a Blob and a temporary link. - If you do not control the page, a tool such as LightCube Data can extract the table for you instead.
What is an HTML table and why convert it to CSV?
An HTML table is markup made of a table element containing rows (tr) and cells (th for headers, td for data). A spreadsheet expects a grid of values separated by a delimiter, with one record per line. CSV is the simplest version of that: plain text, comma-separated, one row per line.
Converting the table gives you a file you can sort, filter, pivot, chart, or merge with other data. It also strips away styling, sorting controls, and pagination that make a live web table awkward to work with. One caveat: only real table markup exports cleanly. A layout built from div elements has no rows or cells for a script to read.
How do you export an HTML table to CSV with plain JavaScript?
Start with a table that has an id so your script can select it:
<table id="data-table">
<thead>
<tr><th>Region</th><th>Campaign</th><th>Leads</th><th>Cost</th></tr>
</thead>
<tbody>
<tr><td>North</td><td>Spring launch</td><td>120</td><td>$1,400</td></tr>
<tr><td>South</td><td>Spring launch</td><td>95</td><td>$980</td></tr>
</tbody>
</table>
Then follow these steps:
- Select the table element with
document.getElementById("data-table")and keep a reference to it. - Collect every row with
table.querySelectorAll("tr")and turn the NodeList into an array usingArray.from. - Decide whether the header row should be included. The default is to keep it, and you can drop it later by removing the first row when the table has
thcells inside athead. - Find the widest row by counting
row.children.lengthfor each row. That number becomes your column count. - Convert each cell into a safe CSV value: read
textContent, double any double quotes, and wrap the value in quotes if it contains a comma, a quote, or a line break. - Build one string per row, adding a comma between columns and an empty value wherever a row has no cell at that position.
- Join the rows with line breaks, create a Blob with the
text/csvtype, and trigger the download from a temporary link.
Here is the full exporter class:
class TableCsvExporter {
constructor(table, includeHeaders = true) {
this.table = table;
this.rows = Array.from(table.querySelectorAll("tr"));
const hasHeaderCells = table.querySelectorAll("thead th").length > 0;
if (!includeHeaders && hasHeaderCells) {
this.rows.shift();
}
}
findLongestRowLength() {
return this.rows.reduce((longest, row) => {
const count = row.children.length;
return count > longest ? count : longest;
}, 0);
}
static parseCell(cell) {
let value = cell.textContent.trim();
value = value.replace(/"/g, '""');
if (/[",\n\r]/.test(value)) {
value = `"${value}"`;
}
return value;
}
convertToCSV() {
const lines = [];
const columnCount = this.findLongestRowLength();
for (const row of this.rows) {
let line = "";
for (let i = 0; i < columnCount; i++) {
const cell = row.children[i];
line += cell ? TableCsvExporter.parseCell(cell) : "";
if (i < columnCount - 1) line += ",";
}
lines.push(line);
}
return lines.join("\n");
}
}
How do you handle commas, quotes, and line breaks in CSV values?
A comma is the delimiter, so a raw comma inside a value would shift every following value into the wrong column. The fix is to wrap that value in double quotes. A double quote inside a value is escaped by doubling it. Line breaks inside a cell are treated the same way as commas, because they would otherwise split one record into two.
For the example table above, the output is:
Region,Campaign,Leads,Cost
North,Spring launch,120,"$1,400"
South,Spring launch,95,"$980"
The cost values are quoted because they contain a comma. A cell containing He said "hello" becomes "He said ""hello""". If you trim cell text, note that leading and trailing spaces are removed, so keep the trim only if your data does not rely on them.
What happens when table rows have different numbers of columns?
Real tables often have a short row, a missing cell, or a row that was built with fewer columns than the rest. If you simply join whatever cells exist, that row ends up with fewer delimiters and the columns after it shift left in the spreadsheet.
The fix is to measure the longest row first, then loop every row across that same number of columns. When a row has no cell at a given index, write an empty value instead of a comma. A four-column table with one three-column row produces a line with a trailing empty field, so every line keeps the same column count and the grid stays aligned.
Should the exported CSV include the header row?
Both versions are useful, so make it an option. The constructor takes the table plus an includeHeaders flag that defaults to true. When the flag is false and the table has th cells inside a thead, the first row is removed from the row array before conversion.
Keeping headers is usually right for analysis, because the column names travel with the data. Dropping them is handy when you are appending the file to an existing sheet that already has a header row, or when the table uses a banner row that is not really a column label.
How do you trigger the download from a button?
The CSV string has to become a file. Create a Blob from the text, generate a temporary object URL for it, point a hidden anchor element at that URL, set a readable file name with the download attribute, and click the link:
const table = document.getElementById("data-table");
const exporter = new TableCsvExporter(table, true);
const csvText = exporter.convertToCSV();
const blob = new Blob([csvText], { type: "text/csv;charset=utf-8;" });
const blobUrl = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = blobUrl;
link.download = "table-export.csv";
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(blobUrl), 500);
Wrap that block in a click handler on your export button. The download attribute is what gives the file a readable name instead of a random string. The delayed URL.revokeObjectURL call releases the browser's reference to the blob so memory is not held longer than needed, and the small timeout keeps the download from being cancelled in some versions of Edge.
How do you export HTML tables to Excel or Google Sheets?
CSV is the interchange format, but most people want the result to land directly in a spreadsheet. Here is how the main approaches compare:
| Method | Where it runs | Header handling | Special characters | Best for |
|---|---|---|---|---|
| Plain JavaScript on your own page | In the browser, on a page you control | Optional, on or off | Escaped by your parser | Developers adding an export button |
| Browser extension for table extraction | In the browser, on any page you visit | Kept as displayed | Handled for you | Analysts and marketers copying live tables |
| Web table extraction tool | In the browser, without editing page code | Kept as displayed | Handled for you | One-off jobs and shared workflows |
When you do not own the page, writing a script is not practical, because the table may be rendered by JavaScript, hidden behind pagination, or rebuilt on every scroll. LightCube Data covers that case with a browser extension and a web tool that extract tables from any web page and send them to CSV, Excel, or Google Sheets. If you do own the page, the script above gives you full control over headers and formatting.
What should you check if the export does not work?
Check the source first. If the page uses div elements styled to look like a table, there are no tr or td elements to read, and no script can recover the grid reliably. If the table is built after the page loads, run your code after the table exists or use a callback that fires when it appears.
Next, check the file itself. A CSV that opens in a single column usually means the delimiter does not match your locale settings, so import it with a comma separator instead of a tab or semicolon. Missing values in the middle of a row point back to the column padding logic. Garbled characters such as accented names or symbols mean the Blob type needs charset=utf-8. Finally, confirm that the browser supports the modern JavaScript features used here, including classes, const, arrow functions, Array.from, Blob, and URL.createObjectURL.
Export any web table to CSV or Excel
Paste a page link into the LightCube web exporter and download its tables as CSV or Excel. Free for 25 rows; Pro is $9 once.
Try the web exporter ↗FAQ
Can I export an HTML table to CSV without writing JavaScript?
Yes. If the table lives on a page you do not control, use a table extraction tool instead of a script. A browser extension can capture the table as it appears on the page and deliver it as CSV, Excel, or a Google Sheets file, which is faster than copying cells by hand.
Will the exported CSV open in Excel and Google Sheets?
Yes. A comma-separated text file opens directly in Excel, Google Sheets, Numbers, and most CSV viewers. For Google Sheets you can upload the file or paste the text into a cell and use Data > Split text to columns. Keep the UTF-8 charset in the Blob type so accented characters survive the trip.
How are commas and double quotes inside cells handled?
Any value containing a comma, a double quote, or a line break is wrapped in double quotes, and embedded double quotes are doubled. That is the standard CSV escaping rule, so a cost of $1,400 stays in one column and a cell reading He said "hello" stays readable.
What if some rows have fewer columns than others?
The exporter measures the longest row and writes an empty value for any missing cell, so every line contains the same number of delimiters. Columns stay aligned when the file opens, and the missing values appear as blank cells rather than shifted data.
Does this work in Internet Explorer and older browsers?
Not as written. The code uses modern features such as class syntax, const, arrow functions, Array.from, Blob, and URL.createObjectURL, which Internet Explorer does not support. Current versions of Chrome, Firefox, Edge, and Safari run it without changes, and older browsers would need the code rewritten in older syntax.
Based on a video by dcode: How to export an HTML table to a CSV file in JavaScript - Project Video. Written in our own words with added steps and an FAQ.