Export HTML Table to Excel using JavaScript

  1. Use the TabletoExcel library to export HTML table to Excel in JavaScript
  2. Use the TableExport library to export HTML table to excel file in JavaScript
  3. Use the jQuery library to export HTML table to excel file in JavaScript

Excel spreadsheets are used to store tabular data in one or more sheets.

In this tutorial, we will learn how to export HTML Table to Excel Using JavaScript.

Use the TabletoExcel library to export HTML table to Excel in JavaScript

The TableToExcel library can be used to export an HTML table to an excel file. We will use the convert() method to make the necessary conversion.

See the code below.

<button id="btnExport" onclick="exportReportToExcel(this)">Export HTML Table</button>

<script type="text/javascript">
  function exportReportToExcel() {
    let table = document.getElementsByID("table");
    TableToExcel.convert(table[0], { 
      name: `file.xlsx`,
      sheet: {
        name: 'Sheet 1'
      }
    });
  }
</script>

In the above example, we get the required table element using the getElementsbyID() function. We export this to an excel file. The name of the file and the sheet were also provided using the name and sheet property.

Use the TableExport library to export HTML table to excel file in JavaScript

The TableExport library can export HTML tables to XLSX, XLS, CSV, or text files. This library is simple to use and provides a wide range of properties to customize the final file.

Check the code below.

<script src="https://cdnjs.cloudflare.com/ajax/libs/TableExport/5.2.0/js/tableexport.min.js" integrity="sha512-XmZS54be9JGMZjf+zk61JZaLZyjTRgs41JLSmx5QlIP5F+sSGIyzD2eJyxD4K6kGGr7AsVhaitzZ2WTfzpsQzg==" crossorigin="anonymous" referrerpolicy="no-referrer">
TableExport(document.getElementsByTagName("table"), {
    filename: 'excelfile',            
    sheetname: "sheet1"                     
});
</script>

In the above example, we access the required HTML table using the getElementsByTagName() function. We used the filename and sheetname property to set the final file’s and the sheet’s names.

Note that to include TableExport library, we added the source for the library in the script tag in the HTML code.

Use the jQuery library to export HTML table to excel file in JavaScript

We will use the table2excel plugin to export HTML table data to an Excel spreadsheet. It is a lightweight jQuery plugin.

Check the code below.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", type="text/javascript">
  function Export() {
    $("#table").table2excel({
      filename: "file.xls"
    });
  }
</script>

We accessed the required table using the $(table). The table2excel constructor converted this to the required file.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.