How To Export Data From Html Table To Excel Use JavaScript

This example will tell you how to use JavaScript to export an Html table data to an Excel file and download it.

1. Export Data From Html Table To Excel JavaScript Source Code.

  1. Below is an Html web page source code, it contains a snippet of JavaScript code at the end of the page.
  2. You can save the below source code to a local Html file.
  3. When you browse the below Html page in a web browser, it will display a Html table and a link at top of the table. When you click the link, it will export the Html table data to a local Excel file.
  4. Below is the web page picture.
    export html table data to an excel file use javascript
  5. Below is the source code.
    <!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>How To Export Data From Html Table To Excel Use JavaScript</title>
        /* This style is only used when browse this page in a web browser, excel will not separate the table border, so this style is not needed */
        table {
            border-collapse: collapse;
    <a href='' id='dd'>Export Html Table To Excel</a>
    <!-- Set border="1" to show table borders -->
    <table border="1">
        <!-- The caption element can generate the table title, and its cell column span is the number of columns in the table -->
        <caption>Student Record</caption>
            <!-- You can use rowspan and colspan to merge cells -->
            <th rowspan="2">ID</th>
            <th rowspan="2">Student ID</th>
            <th rowspan="2">Name</th>
            <th rowspan="2">Sex</th>
            <th rowspan="2">Age</th>
            <th colspan="3">Score</th>
         <tr style='display:none'>
        // Use the outerHTML attribute to get the HTML code of the entire table element (including the <Table> tag), and then wrap it into a complete HTML document. Set charset to urf-8 to prevent garbled code
        var html = "<html><head><meta charset='utf-8' /></head><body>" + document.getElementsByTagName("table")[0].outerHTML + "</body></html>";
        // Instantiate a Blob object. The first parameter of its constructor is an array containing file contents, and the second parameter is an object containing file type attributes
        var blob = new Blob([html], { type: "application/" });
        var a = document.getElementById("dd");
        // Use URL.createObjectURL() method to generate the Blob URL for the a tag.
        a.href = URL.createObjectURL(blob);
        // Set the download file name. = "student-record.xls";

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.