Categories
JavaScript Answers

How to export HTML table to excel using JavaScript?

Spread the love

Sometimes, we want to export HTML table to excel using JavaScript.

In this article, we’ll look at how to export HTML table to excel using JavaScript.

How to export HTML table to excel using JavaScript?

To export HTML table to excel using JavaScript, we can select the table, get its HTML, and encode it into a base64 string.

For instance, we write:

<table id="table">
  <thead>
    <tr>
      <th>name</th>
      <th>place</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>adfas</td>
      <td>asdfasf</td>
    </tr>
  </tbody>
</table>

to add a table.

Then we write:

const table = document.getElementById('table');
const html = table.outerHTML;
window.open('data:application/vnd.ms-excel;base64,' + btoa(html));

to select the table with getElementById.

And then we get its HTML code with outerHTML.

Next, we call btoa to convert the table HTML string into a base64 string.

And we concatenate the 'data:application/vnd.ms-excel;base64,' MIME type before it.

Then we download it with window.open.

Conclusion

To export HTML table to excel using JavaScript, we can select the table, get its HTML, and encode it into a base64 string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *