Export html table to excel in html

The reason the solution you found on the internet is no working is because of the line that starts var colCount. The variable mytable only has two elements being <thead> and <tbody>. The var colCount line is looking for all the elements within mytable that are <tr>. The best thing you can do is give an id to your <thead> and <tbody> and then grab all the values based on that. Say you had <thead id='headers'> :

function write_headers_to_excel() 
{
  str="";

  var myTableHead = document.getElementById('headers');
  var rowCount = myTableHead.rows.length;
  var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").length; 

var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;

for(var i=0; i<rowCount; i++) 
{   
    for(var j=0; j<colCount; j++) 
    {           
        str= myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
        ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
    }
}

}

and then do the same thing for the <tbody> tag.

EDIT: I would also highly recommend using jQuery. It would shorten this up to:

function write_to_excel() 
{
 var ExcelApp = new ActiveXObject("Excel.Application");
 var ExcelSheet = new ActiveXObject("Excel.Sheet");
 ExcelSheet.Application.Visible = true; 

  $('th, td').each(function(i){
    ExcelSheet.ActiveSheet.Cells(i+1,i+1).Value = this.innerHTML;
  });
}

Now, of course, this is going to give you some formatting issues but you can work out how you want it formatted in Excel.

EDIT: To answer your question about how to do this for n number of tables, the jQuery will do this already. To do it in raw Javascript, grab all the tables and then alter the function to be able to pass in the table as a parameter. For instance:

var tables = document.getElementsByTagName('table');
for(var i = 0; i < tables.length; i++)
{
  write_headers_to_excel(tables[i]);
  write_bodies_to_excel(tables[i]);
}

Then change the function write_headers_to_excel() to function write_headers_to_excel(table). Then change var myTableHead = document.getElementById('headers'); to var myTableHead = table.getElementsByTagName('thead')[0];. Same with your write_bodies_to_excel() or however you want to set that up.

  1. Home
  2. JavaScript
  3. Export HTML Table Data to Excel using JavaScript

By: CodexWorld
|
In: JavaScript
|
Last Updated: Jun 7, 2021

Export data to Excel is very useful on the data list for nearly every web application. The export feature helps to download the data list as a file format for offline use. Excel format is ideal for exporting data in a file. Mostly the server-side method is used for export data to excel using PHP. But if you want a client-side solution to export table data to excel, it can be easily done using JavaScript.

The client-side export functionality makes the web application user-friendly. Using JavaScript, the HTML table data can be easily exported without page refresh. In this tutorial, we will show you how to export HTML table data to excel using JavaScript. The JavaScript export functionality can be used in the member list, product list, or other lists to download the data list in excel file format.

Export HTML Table Data to Excel

JavaScript Code:
The exportTableToExcel() function convert HTML table data to excel and download as XLS file (.xls).

  • tableID – Required. Specify the HTML table ID to export data from.
  • filename – Optional. Specify the file name to download excel data.
function exportTableToExcel(tableID, filename = ''){
    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
    
    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';
    
    // Create download link element
    downloadLink = document.createElement("a");
    
    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
    
        // Setting the file name
        downloadLink.download = filename;
        
        //triggering the function
        downloadLink.click();
    }
}

HTML Table Data:
The HTML table contains some users data with some basic fields like name, email, country.

<table id="tblData">
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Country</th>
    </tr>
    <tr>
        <td>John Doe</td>
        <td>john@gmail.com</td>
        <td>USA</td>
    </tr>
    <tr>
        <td>Michael Addison</td>
        <td>michael@gmail.com</td>
        <td>UK</td>
    </tr>
    <tr>
        <td>Sam Farmer</td>
        <td>sam@gmail.com</td>
        <td>France</td>
    </tr>
</table>

The button triggers exportTableToExcel() function to export HTML table data using JavaScript.

<button onclick="exportTableToExcel('tblData')">Export Table Data To Excel File</button>

If you want to export data with the custom file name, pass your desired file name in the exportTableToExcel() function.

<button onclick="exportTableToExcel('tblData', 'members-data')">Export Table Data To Excel File</button>

Export Data to Excel in PHP

Conclusion

Our example code helps you to add export functionality in the HTML table without any third-party jQuery plugin or server-side script. You can easily export the table data using minimal JavaScript code. Also, the functionality of the example code can be enhanced or customized easily as per your needs.

  • DataTables
  • Excel
  • Export
  • JavaScript

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community — Ask Question

RELATED TUTORIALS

Leave a reply

In this tutorial you can find the solution of How to Export or Download the HTML Table Data in Excel Sheet by using JavaScript. Exporting Data to Excel is required feature in our web application. Because by export data functionality will helps to download data from web application to different file format for offline use of data and for this excel format is an ideal for exporting data in file for offline use. There many tutorial we have published for export data to excel at server side scripting using PHP. But if we can perform at client-side for export data into Excel sheet, so it will reduce load on server. So for this for export data to excel , here we will use JavaScript for perform client-side export data to excel sheet.

The client-side export feature will makes our web application more user-friendly. So with the help of JavaScript, we can export HTML table data to Excel format without refresh of web page. Under this tutorial, you can learn How to export HTML table data to excel using JavaScript. In this tutorial, we will use SheetJS JavaScript Library for export HTML table data to Excel.

How to Export Html Table to Excel Sheet using JavaScript

  1. HTML Table Data:
  2. JavaScript Code:

1. HTML Table Data

For Export HTML data to Excel, here first we have to load some data in HTML table. So here we have make fetch employee table data and load in HTML table with table column like name, address, gender, designation and age. Here we have create HTML table with id employee_data. So this id we will use for fetch this HTML table data in JavaScript code. Under this HTML code we have make one button tag with id export_button, so when use has click on this button, then HTML table data will be download in Excel file format without refresh of web page using JavaScript.


<?php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$query = "SELECT * FROM tbl_employee ORDER BY name ASC";

$result = $connect->query($query);

?>

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8" />
	<title>Export HTML table data to excel using JavaScript</title>
	<meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>
</head>
<body>
    <div class="container">
    	<h2 class="text-center mt-4 mb-4">Export HTML table data to excel using JavaScript</h2>
    	<div class="card">
    		<div class="card-header">
    			<div class="row">
    				<div class="col col-md-6">Sample Data</div>
    				<div class="col col-md-6 text-right">
    					<button type="button" id="export_button" class="btn btn-success btn-sm">Export</button>
    				</div>
    			</div>
    		</div>
    		<div class="card-body">
    			<table id="employee_data" class="table table-striped table-bordered">
                    <tr>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Gender</th>
                        <th>Designation</th>
                        <th>Age</th>
                    </tr>
                    <?php
                    foreach($result as $row)
                    {
                        echo '
                        <tr>
                            <td>'.$row["name"].'</td>
                            <td>'.$row["address"].'</td>
                            <td>'.$row["gender"].'</td>
                            <td>'.$row["designation"].'</td>
                            <td>'.$row["age"].'</td>
                        </tr>
                        ';
                    }
                    ?>
                </table>
    		</div>
    	</div>
    </div>
</body>
</html>

2. JavaScript Code

In this tutorial, we have use SheetJS JavaScript Library for export HTML table data to Excel using JavaScript. So first we have to include following SheetJS library link at header of this HTML web page.


<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>

In JavaScript code part, first we have make html_table_to_excel(type) function. This function has use SheetJS Library function and convert or Write HTML table data to Excel format and download in browser without refresh of web page.

Once function is ready then we have to called html_table_to_excel(type) function on button click event, so for trigger button click event, we have use addEventListener method. So when user has click on button then html_table_to_excel(type) function has been called with xlsx file type. So it will download HTML table data in .xlsx format Excel file in browser without refresh of web page at client-side.


function html_table_to_excel(type)
    {
        var data = document.getElementById('employee_data');

        var file = XLSX.utils.table_to_book(data, {sheet: "sheet1"});

        XLSX.write(file, { bookType: type, bookSST: true, type: 'base64' });

        XLSX.writeFile(file, 'file.' + type);
    }

    const export_button = document.getElementById('export_button');

    export_button.addEventListener('click', () =>  {
        html_table_to_excel('xlsx');
    });

Conclusion

This tutorial will helps you to add export feature of download HTML table data in Excel sheet without using third-party jQuery plugin or any server-side script. By follow this tutorial you can easily export HTML table data to Excel using minimal JavaScript code.

If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.

Table to Excel 2

Build Status

Export HTML table to valid excel file effortlessly.
This library uses exceljs/exceljs under the hood to create the excel.
(Initial version of this library was using protobi/js-xlsx, it can be found here)

Installation

Browser

Just add a script tag:

<script type="text/javascript" src="../dist/tableToExcel.js"></script>

Node

npm install @linways/table-to-excel --save
import TableToExcel from "@linways/table-to-excel";

Usage

Create your HTML table as normal.
To export content of table #table1 run:

TableToExcel.convert(document.getElementById("table1"));

or

TableToExcel.convert(document.getElementById("table1"), {
  name: "table1.xlsx",
  sheet: {
    name: "Sheet 1"
  }
});

Check this pen for working example.

Cell Types

Cell types can be set using the following data attributes:

Attribute Description Possible Values
data-t To specify the data type of a cell s : String (Default)
n : Number
b : Boolean
d : Date
data-hyperlink To add hyper link to cell External URL or hyperlink to another sheet
data-error To add value of a cell as error

Example:

<!-- for setting a cell type as number -->
<td data-t="n">2500</td>
<!-- for setting a cell type as date -->
<td data-t="d">05-23-2018</td>
<!-- for setting a cell type as boolean. String "true/false" will be accepted as Boolean-->
<td data-t="b">true</td>
<!-- for setting a cell type as boolean using integer. 0 will be false and any non zero value will be true -->
<td data-t="b">0</td>
<!-- For adding hyperlink -->
<td data-hyperlink="https://google.com">Google</td>

Cell Styling

All styles are set using data attributes on td tags.
There are 5 types of attributes: data-f-*, data-a-*, data-b-*, data-fill-* and data-num-fmt which corresponds to five top-level attributes font, alignment, border, fill and numFmt.

Category Attribute Description Values
font data-f-name Font name «Calibri» ,»Arial» etc.
data-f-sz Font size «11» // font size in points
data-f-color Font color A hex ARGB value. Eg: FFFFOOOO for opaque red.
data-f-bold Bold true or false
data-f-italic Italic true or false
data-underline Underline true or false
data-f-strike Strike true or false
Alignment data-a-h Horizontal alignment left, center, right, fill, justify, centerContinuous, distributed
data-a-v Vertical alignment bottom, middle, top, distributed, justify
data-a-wrap Wrap text true or false
data-a-indent Indent Integer
data-a-rtl Text direction: Right to Left true or false
data-a-text-rotation Text rotation 0 to 90
-1 to -90
vertical
Border data-b-a-s Border style (all borders) Refer BORDER_STYLES
data-b-t-s Border top style Refer BORDER_STYLES
data-b-b-s Border bottom style Refer BORDER_STYLES
data-b-l-s Border left style Refer BORDER_STYLES
data-b-r-s Border right style Refer BORDER_STYLES
data-b-a-c Border color (all borders) A hex ARGB value. Eg: FFFFOOOO for opaque red.
data-b-t-c Border top color A hex ARGB value.
data-b-b-c Border bottom color A hex ARGB value.
data-b-l-c Border left color A hex ARGB value.
data-b-r-c Border right color A hex ARGB value.
Fill data-fill-color Cell background color A hex ARGB value.
numFmt data-num-fmt Number Format «0»
«0.00%»
«0.0%» // string specifying a custom format
«0.00%;(0.00%);-;@» // string specifying a custom format, escaping special characters

BORDER_STYLES: thin, dotted, dashDot, hair, dashDotDot, slantDashDot, mediumDashed, mediumDashDotDot, mediumDashDot, medium, double, thick

Exclude Cells and rows

To exclude a cell or a row from the exported excel add data-exclude="true" to the corresponding td or tr.
Example:

<!-- Exclude entire row -->
<tr data-exclude="true">
  <td>Excluded row</td>
  <td>Something</td>
</tr>

<!-- Exclude a single cell -->
<tr>
  <td>Included Cell</td>
  <td data-exclude="true">Excluded Cell</td>
  <td>Included Cell</td>
</tr>

Column Width

Column width’s can be set by specifying data-cols-width in the <table> tag.
data-cols-width accepts comma separated column widths specified in character count .
data-cols-width="10,20" will set width of first coulmn as width of 10 charaters and second column as 20 characters wide.
Example:

<table data-cols-width="10,20,30">
  ...
</table>

Row Height

Row Height can be set by specifying data-height in the <tr> tag.
Example:

<tr data-height="42.5">
  <td>Cell 1</td>
  <td>Cell 2</td>
</tr>

Release Changelog

1.0.0

Migration Guide for migrating from V0.2.1 to V1.0.0

  • Changed the backend to Exceexceljs/exceljslJS
  • Added border color
  • Option to set style and color for all borders
  • Exclude row
  • Added text underline
  • Added support for hyperlinks
  • Text intent
  • RTL support
  • Extra alignment options
  • String «true/false» will be accepted as Boolean
  • Changed border style values
  • Text rotation values changed

1.0.2

  • Fixed bug in handling multiple columns merges in a sheet

1.0.3

  • Option to specify row height

Contents

  • 1 HTML table
  • 2 Javascript array
    • 2.1 Example : Download the HTML table in Excel (.csv) format
      • 2.1.1 Step 1 : Create the HTML table
      • 2.1.2 Step 2 : Add CSS properties to style the table
      • 2.1.3 Step 3 : Create the download button
      • 2.1.4 Step 4 : Implement Javascript function to download the HTML table in CSV file.
      • 2.1.5 Step 5 : Call the Javascript function using onclick event
    • 2.2 Complete code for reference :

HTML providing the <table> tag to show the data in row and column format. We might have seen those tables in several web pages. Example: Stock Price list,Employee salary reports, Student marks report and so on. The below image is showing the corona cases report in HTML table format.

Corona cases report in HTML table

Corona cases report in HTML table

If we have the option to download those tables in excel, It would be helpful to analyze the data. Lets create the sample table using HTML and enable the download option using Javascript.

Javascript array

Javascript array is used to store collection of values in a single variable. As we know, the HTML table has a collection of rows and columns. We can add those values into array. Then the delimiters will be added for each row and column values to create the excel record.

var result = [‘Company’,’Group’,’Previous Value’,’Current Value’]

  • Each row in a table delimited by new line character (n)
  • Each column in a table delimited by comma character (,)

Example : Download the HTML table in Excel (.csv) format

In this example, we are going to create the stock price list table with the download button – To export the table in csv file.

Step 1 : Create the HTML table

The below HTML code creates the stock price list table.

  • <table> – Defines HTML table which contains set of rows and column values
  • <tr> – It creates row element in the table.
  • <th> – The header cell value created in this tag.
  • <td> – Defines data cell/column of the table.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<html>

<head>

    <title>Export HTML data to excel </title>

    <h2>US NASDAQ Stocks price list </h2>

</head>

<body>

        <table id=«tblStocks» cellpadding=«0» cellspacing=«0»>

            <tr>

                <th>Company</th>

                <th>Group</th>

                <th>Prev Close($)</th>

                <th>Current Price($)</th>

                <th>Change(%)</th>

              </tr>

              <tr>

                <td>Life HealthCare INC</td>

                <td>A</td>

                <td>35.58</td>

                <td>38.45</td>

                <td>+8.06</td>

              </tr>

              <tr>

                <td>Den Networks Ltd</td>

                <td>A</td>

                <td>72.55</td>

                <td>77.60</td>

                <td>+6.96</td>

              </tr>

              <tr>

                <td>RMG Cements</td>

                <td>B</td>

                <td>140</td>

                <td>135</td>

                <td>3.57</td>

              </tr>

        </table>

        <br />

</body>

</html>

HTML table example

HTML table example

Step 2 : Add CSS properties to style the table

In the HTML code, id (tblStocks) is defined for the <table> tag. For that id, We can add the CSS properties (margin,colour,font style) which will change the table style.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<style>

        #tblStocks {

          font-family: «Trebuchet MS», Arial, Helvetica, sans-serif;

          border-collapse: collapse;

          width: 100%;

        }

        #tblStocks td, #tblStocks th {

          border: 1px solid #ddd;

          padding: 8px;

        }

        #tblStocks tr:nth-child(even){background-color: #f2f2f2;}

        #tblStocks tr:hover {background-color: #ddd;}

        #tblStocks th {

            padding-top: 12px;

            padding-bottom: 12px;

            text-align: left;

            background-color: #294c67;;

            color: white;

          }

      </style>

Change the table style using CSS

HTML table with CSS properties

Step 3 : Create the download button

Bootstrap providing the graphical icons from the Glyphicon Halflings set. Lets create the button with download icon using Glypicons.

<link rel=«stylesheet» href=«https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css»>

<button>

   <span class=«glyphicon glyphicon-download»></span>

   Download list

</button>

Add download button using Glyphicon

Add download button using Glyphicon

Step 4 : Implement Javascript function to download the HTML table in CSV file.

  • Get the HTML table into Javascript variable using id “tblStocks” which is assigned for <table> tag.
  • Loop through the variable to fetch cell values and add those values into javascript array. Here we are having array inside a array which means the outer array contains number of rows and each inner array contains number of columns for each row.

rows = [

[column1,column2,column3,column4,column5],

[column1,column2,column3,column4,column5],...

]

  • Create <a> tag element with download attribute which used to download the data when user clicks the button. Here we are specifying data format as csv.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

function exportData(){

    /* Get the HTML data using Element by Id */

    var table = document.getElementById(«tblStocks»);

    /* Declaring array variable */

    var rows =[];

      //iterate through rows of table

    for(var i=0,row; row = table.rows[i];i++){

        //rows would be accessed using the «row» variable assigned in the for loop

        //Get each cell value/column from the row

        column1 = row.cells[0].innerText;

        column2 = row.cells[1].innerText;

        column3 = row.cells[2].innerText;

        column4 = row.cells[3].innerText;

        column5 = row.cells[4].innerText;

    /* add a new records in the array */

        rows.push(

            [

                column1,

                column2,

                column3,

                column4,

                column5

            ]

        );

        }

        csvContent = «data:text/csv;charset=utf-8,»;

         /* add the column delimiter as comma(,) and each row splitted by new line character (n) */

        rows.forEach(function(rowArray){

            row = rowArray.join(«,»);

            csvContent += row + «rn»;

        });

        /* create a hidden <a> DOM node and set its download attribute */

        var encodedUri = encodeURI(csvContent);

        var link = document.createElement(«a»);

        link.setAttribute(«href», encodedUri);

        link.setAttribute(«download», «Stock_Price_Report.csv»);

        document.body.appendChild(link);

         /* download the data file named «Stock_Price_Report.csv» */

        link.click();

}

Step 5 : Call the Javascript function using onclick event

Here we have created the javascript function in different file which named as “downloadFile.js”. Include that file in HTML using <script> tag. This script tag should be placed inside the <head> tag.

<script type=«text/javascript» src=«downloadFile.js»></script>

Finally create the onclick event for the Download List button to call the javascript function exportData().

<button onclick=«exportData()»>

    <span class=«glyphicon glyphicon-download»></span>

    Download list

</button>

As you can see below, the HTML table downloaded in the csv file(Stock_Price_Report.csv) when user clicks the Download list button

Download HTML table in CSV

Download HTML table in CSV

HTML table downloaded in CSV file (Stock_Price_Report.csv)

Create csv file in Javascript

Create csv file in Javascript

Complete code for reference :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

<html>

<head>

    <title>Export HTML data to excel </title>

    <h2>US NASDAQ Stocks price list </h2>

    <link rel=«stylesheet» href=«https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css»>

    <script type=«text/javascript» src=«downloadFile.js»></script>

    <style>

        #tblStocks {

          font-family: «Trebuchet MS», Arial, Helvetica, sans-serif;

          border-collapse: collapse;

          width: 100%;

        }

        #tblStocks td, #tblStocks th {

          border: 1px solid #ddd;

          padding: 8px;

        }

        #tblStocks tr:nth-child(even){background-color: #f2f2f2;}

        #tblStocks tr:hover {background-color: #ddd;}

        #tblStocks th {

            padding-top: 12px;

            padding-bottom: 12px;

            text-align: left;

            background-color: #294c67;;

            color: white;

          }

      </style>

</head>

<body>

        <table id=«tblStocks» cellpadding=«0» cellspacing=«0»>

            <tr>

                <th>Company</th>

                <th>Group</th>

                <th>Prev Close($)</th>

                <th>Current Price($)</th>

                <th>Change(%)</th>

              </tr>

              <tr>

                <td>Life HealthCare INC</td>

                <td>A</td>

                <td>35.58</td>

                <td>38.45</td>

                <td>+8.06</td>

              </tr>

              <tr>

                <td>Den Networks Ltd</td>

                <td>A</td>

                <td>72.55</td>

                <td>77.60</td>

                <td>+6.96</td>

              </tr>

              <tr>

                <td>RMG Cements</td>

                <td>B</td>

                <td>140</td>

                <td>135</td>

                <td>3.57</td>

              </tr>

        </table>

        <br />

        <button onclick=«exportData()»>

            <span class=«glyphicon glyphicon-download»></span>

            Download list</button>

</body>

</html>

Javascript file : downloadFile.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

function exportData(){

    /* Get the HTML data using Element by Id */

    var table = document.getElementById(«tblStocks»);

    /* Declaring array variable */

    var rows =[];

      //iterate through rows of table

    for(var i=0,row; row = table.rows[i];i++){

        //rows would be accessed using the «row» variable assigned in the for loop

        //Get each cell value/column from the row

        column1 = row.cells[0].innerText;

        column2 = row.cells[1].innerText;

        column3 = row.cells[2].innerText;

        column4 = row.cells[3].innerText;

        column5 = row.cells[4].innerText;

    /* add a new records in the array */

        rows.push(

            [

                column1,

                column2,

                column3,

                column4,

                column5

            ]

        );

        }

        csvContent = «data:text/csv;charset=utf-8,»;

         /* add the column delimiter as comma(,) and each row splitted by new line character (n) */

        rows.forEach(function(rowArray){

            row = rowArray.join(«,»);

            csvContent += row + «rn»;

        });

        /* create a hidden <a> DOM node and set its download attribute */

        var encodedUri = encodeURI(csvContent);

        var link = document.createElement(«a»);

        link.setAttribute(«href», encodedUri);

        link.setAttribute(«download», «Stock_Price_Report.csv»);

        document.body.appendChild(link);

         /* download the data file named «Stock_Price_Report.csv» */

        link.click();

}

Recommended Articles

  • How to make blinking text using HTML and CSS?
  • How to show the Text letter by letter using CSS?

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Any HTML table that you have created can be converted into an Excel Spreadsheet by using jQuery and it is compatible with all browsers. There are two simple approaches that require basic HTML and jQuery knowledge to achieve this.

    • Approach 1: Using jQuery plugin: A simple jQuery plugin ‘table2excel’ can be used for converting an HTML table to an excel sheet. 

    Syntax:

    $("#table-id").table2excel({
        filename: "excel_sheet-name.xls"
    });
    • Example: 

    html

    <table id="studtable">

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Age</th>

            <th>Address</th>

        </tr>

        <tr>

            <td>101</td>

            <td>Alex</td>

            <td>15</td>

            <td>Maldives</td>

        </tr>

        <tr>

            <td>102</td>

            <td>Chris</td>

            <td>14</td>

            <td>Canada</td>

        </tr>

        <tr>

            <td>103</td>

            <td>Jay</td>

            <td>15</td>

            <td>Toronto</td>

        </tr>

    </table>

    <script>

     $(document).ready(function () {

        $("#studtable").table2excel({

            filename: "Students.xls"

        });

     });

    </script>

    • Output:
     
    ID    Name    Age    Address
    101    Alex    15    Maldives
    102    Chris    14    Canada
    103    Jay    15    Toronto
    • The above output gets converted into an Excel spreadsheet in the exact same manner the HTML table is. About ‘table2excel’: The ‘table2excel’ is a simple yet useful jQuery plugin that allows for exporting HTML table data to an Excel file. The ‘table2excel’ also has a feature to exclude cells that contain a specified class. Syntax for noExport:
    $(document).ready(function() {
        $("#table-id").table2excel({
            exclude: ".noExport",
            filename: "name-of-the-file",
        });
    });
    • Example code for excluding some specified cells: 

    html

    <script src=

    "//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">

    </script>

    <script src=

    "//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js">

    </script>

    <button>Export</button>

    <table>

        <thead>

            <tr>

                <td class="noExport">

                    This cell will not be exported.

                </td>

                <td>

                    This cell will get exported.

                </td>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>Alex</td>

                <td class="noExport">Maldives</td>

            </tr>

            <tr>

                <td>Chris</td>

                <td>Canada</td>

            </tr>

        </tbody>

    </table>

    • Note: In the above sample code, the class ‘.noExport’ has been used to exclude those specified cells from the HTML table data. Therefore the exported Excel Spreadsheet also does not include those cells from the HTML table data.
    • Approach 2: Using simple HTML: Consider the same students table above to understand the below. Let’s use a button in our code which when clicked to converts the HTML data table into an Excel spreadsheet. Note that the ‘export’ button below does not actually convert the HTML table to an excel sheet. This has to used in a proper and already existing HTML code to get the Excel spreadsheet and will not work in this IDE. 

    html

    <!DOCTYPE html>

    <html>

    <head>

        <title>

            HTML Table To Excel

            spreadsheet using

            HTML only

        </title>

    </head>

    <body>

        <table id="studtable">

            <tr>

                <th>ID</th>

                <th>Name</th>

                <th>Age</th>

                <th>Address</th>

            </tr>

            <tr>

                <td>101</td>

                <td>Alex</td>

                <td>15</td>

                <td>Maldives</td>

            </tr>

            <tr>

                <td>102</td>

                <td>Chris</td>

                <td>14</td>

                <td>Canada</td>

            </tr>

            <tr>

                <td>103</td>

                <td>Jay</td>

                <td>15</td>

                <td>Toronto</td>

            </tr>

        </table>

        <button onclick="tableToExcel(

            'studtable', 'Students')">

            Click to Export

        </button>

    </body>

    </html>

    • Output:

     

    HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps. jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more“. 

    • HTML Tutorial and HTML Examples.
    • jQuery Tutorial and jQuery Examples.

    Like Article

    Save Article

    export-html-table-data-to-excel

    Exporting data to Excel is very useful for every enterprise on data list web application. Every time , export data using custom export feature helps to download table data list for offline use as excel file like csv format. As a web Developer, I was required to do that in various live project. Excel format for exporting data in file is ideal in every enterprises. Mostly we used server-side method to export data to excel using php. But if you want to download table data to excel using client-side view then it can be easily done using javascript.

    Looking for assistance with Excel assignments?

    You should visit https://assignmentcore.com/excel-homework/ and get MS Excel homework help online from a team of experts.

    In this tutorials, we will learn about how to export HTML table data to excel using client-side JavaScript. The Client-side export data functionality makes any web application more user-friendly. Using JavaScript, we can export or download HTML table data in excel format without page refresh.

    HTMl Table Data:
    The Following below HTML Table contains some user data with some basic fields like Name, Email, Age, Mobile.

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    <table id=«tblexportData»>

        <tr>

            <th>Name</th>

            <th>Email</th>

            <th>Age</th>

            <th>Mobile</th>

        </tr>

        <tr>

            <td>Robert</td>

            <td>robert@gmail.com</td>

            <td>26</td>

             <td>9999999999</td>

        </tr>

        <tr>

            <td>Michael</td>

            <td>michael@gmail.com</td>

             <td>24</td>

             <td>9999999999</td>

        </tr>

        <tr>

            <td>Julie</td>

            <td>julie@gmail.com</td>

             <td>36</td>

             <td>9999999999</td>

        </tr>

    <tr>

            <td>Trevor</td>

            <td>trevor@gmail.com</td>

             <td>28</td>

             <td>9999999999</td>

        </tr>

    </table>

    JavaScript Code:

    The exportToExcel() function will use convert HTML table data to excel and download as xls file(.xls).

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    <script type=«text/javascript»>

    function exportToExcel(tableID, filename = »){

        var downloadurl;

        var dataFileType = ‘application/vnd.ms-excel’;

        var tableSelect = document.getElementById(tableID);

        var tableHTMLData = tableSelect.outerHTML.replace(/ /g, ‘%20’);

        // Specify file name

        filename = filename?filename+‘.xls’:‘export_excel_data.xls’;

        // Create download link element

        downloadurl = document.createElement(«a»);

        document.body.appendChild(downloadurl);

        if(navigator.msSaveOrOpenBlob){

            var blob = new Blob([‘ufeff’, tableHTMLData], {

                type: dataFileType

            });

            navigator.msSaveOrOpenBlob( blob, filename);

        }else{

            // Create a link to the file

            downloadurl.href = ‘data:’ + dataFileType + ‘, ‘ + tableHTMLData;

            // Setting the file name

            downloadurl.download = filename;

            //triggering the function

            downloadurl.click();

        }

    }

    </script>

    tableID – Required. Specify the HTML table ID to export data from.
    filename – Optional. Specify the file name to download excel data.

    <button onclick=«exportToExcel(‘tblexportData’)»>Export Table Data To Excel File</button>

    The above button triggers exportToExcel() function to download HTML table data using javascript

    If you want to download or export data with custom file name then you can pass your file name in the exportToExcel() function, see below button code:

    <button onclick=«exportToExcel(‘tblexportData’, ‘user-data’)»>Export Table Data To Excel File</button>

    Complete Code:

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

    76

    77

    78

    79

    80

    81

    82

    83

    84

    85

    86

    <html>

    <head>

    <title>Export HTML Table Data to Excel using JavaScript | Tutorialswebsite</title>

    <link rel=«stylesheet» href=«https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css» >

    <script type=«text/javascript»>

    function exportToExcel(tableID, filename = »){

        var downloadurl;

        var dataFileType = ‘application/vnd.ms-excel’;

        var tableSelect = document.getElementById(tableID);

        var tableHTMLData = tableSelect.outerHTML.replace(/ /g, ‘%20’);

        // Specify file name

        filename = filename?filename+‘.xls’:‘export_excel_data.xls’;

        // Create download link element

        downloadurl = document.createElement(«a»);

        document.body.appendChild(downloadurl);

        if(navigator.msSaveOrOpenBlob){

            var blob = new Blob([‘ufeff’, tableHTMLData], {

                type: dataFileType

            });

            navigator.msSaveOrOpenBlob( blob, filename);

        }else{

            // Create a link to the file

            downloadurl.href = ‘data:’ + dataFileType + ‘, ‘ + tableHTMLData;

            // Setting the file name

            downloadurl.download = filename;

            //triggering the function

            downloadurl.click();

        }

    }

    </script>

    </head>

    <body>

    <div class=«container»>

    <table id=«tblexportData» class=«table»>

    <thead>

        <tr>

            <th>Name</th>

            <th>Email</th>

            <th>Age</th>

            <th>Mobile</th>

        </tr>

    </thead>

      <tbody>

        <tr>

            <td>Robert</td>

            <td>robert@gmail.com</td>

            <td>26</td>

             <td>9999999999</td>

        </tr>

        <tr>

            <td>Michael</td>

            <td>michael@gmail.com</td>

             <td>24</td>

             <td>9999999999</td>

        </tr>

        <tr>

            <td>Julie</td>

            <td>julie@gmail.com</td>

             <td>36</td>

             <td>9999999999</td>

        </tr>

    <tr>

            <td>Trevor</td>

            <td>trevor@gmail.com</td>

             <td>28</td>

             <td>9999999999</td>

        </tr>

    </tbody>

    </table>

    <button onclick=«exportToExcel(‘tblexportData’, ‘user-data’)» class=«btn btn-success»>Export Table Data To Excel File</button>

    </div>

    </body>

    </html>

    Conclusion

    Our example code will help you to easily export the table data using minimal javascript code.

    Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

    Pradeep Maurya

    Pradeep Maurya is the Professional Web Developer & Designer and the Founder of  “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co

    In this article, we will see how we can convert HTML table into excel file using pure javascript function and using jQuery plugin.

    If you are looking to export jQuery Datatable into excel file you can refer the answer described here https://qawithexperts.com/questions/228/how-to-export-html-table-to-pdf-excel-in-jquery-datatable

    Export HTML table to excel (xls) using JavaSript

    Suppose below is our HTML table to be exported

     <table id="tblToExport" cellspacing="0" cellpadding="0">
        <tr>
            <th>Customer Id</th>
            <th>Name</th>
            <th>Country</th>
        </tr>
        <tr>
            <td>1</td>
            <td>Benjamin Hammond</td>
            <td>United States</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Vikas Lalwani</td>
            <td>India</td>
        </tr>
        <tr>
            <td>3</td>
            <td>Martin Mathews</td>
            <td>France</td>
        </tr>
        <tr>
            <td>4</td>
            <td>Geoffry Schidner</td>
            <td>Canada</td>
        </tr>
    </table>
    <br />
    <button id="btnExport" onclick="exportToExcel()"> Export to XLS</button>

    And here is the javascript function which takes HTML table and convert’s it into excel file.

    <script>
    function exportToExcel(){
    var htmls = "";
                var uri = 'data:application/vnd.ms-excel;base64,';
                var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'; 
                var base64 = function(s) {
                    return window.btoa(unescape(encodeURIComponent(s)))
                };
    
                var format = function(s, c) {
                    return s.replace(/{(w+)}/g, function(m, p) {
                        return c[p];
                    })
                };
    
                htmls = document.getElementById("tblToExport").innerHTML;
    
                var ctx = {
                    worksheet : 'Worksheet',
                    table : htmls
                }
    
    
                var link = document.createElement("a");
                link.download = "export.xls";
                link.href = uri + base64(format(template, ctx));
                link.click();
    }
    </script>

    That’s it we are done, you can test it in your browser, output will be as below

    export-html-table-to-excel-using-javascript-min.png

    Export HTML table to Excel using jQuery plugin

    The above Javascript method is good if you want to export HTML table to excel which has few hundred rows, and you don’t need to apply inline CSS in Excel, but what if we have thousand of HTML table rows, I think it is better to use jQuery plugin like Datatable and export jQuery datatable table into excel or you can use jQuery plugin table2excel.js to make everything easy.

    Suppose we have same HTML table as above with little bit changed

    <table id="resultsTable" data-tableName="Test Table 2" class="table table-bordered">
       <thead>
          <tr class="noExl">
             <th>Not Geting exported</th>
             <th>no getting  exported either</th>
          </tr>
          <tr>
             <th>Name(as Header)</th>
             <th>Country(as header)</th>
          </tr>
       </thead>
       <tbody>
          <tr>
             <td>Benjamin Hammond</td>
             <td>United States</td>
          </tr>
          <tr>
             <td>Vikas Lalwani</td>
             <td>India</td>
          </tr>
          <tr>
             <td>Martin Mathews</td>
             <td>France</td>
          </tr>
         <tr>
             <td>Geoffry Schidner</td>
             <td>England</td>
          </tr>
       </tbody>
       <tfoot>
          <tr>
             <td colspan="2">This footer spans 2 cells</td>
          </tr>
       </tfoot>
    </table>
    
    <div class="row">
       <div class="col-md-2">
          <a class="btn btn-default" id="exportNow">Export</a>
       </div>
       <div class="col-md-10"></div>
    </div>

    jQuery and CSS files required to export this table(I am using bootstrap.css just to use some classes of it in HTML and need jQuery as we will use table2excel jQuery plugin which requires jQuery)

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
        
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    
    <script src="https://cdn.rawgit.com/unconditional/jquery-table2excel/master/src/jquery.table2excel.js"></script>

    Complete HTML

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
        
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    
    <script src="https://cdn.rawgit.com/unconditional/jquery-table2excel/master/src/jquery.table2excel.js"></script>
    
        
    
    
    <table id="resultsTable" data-tableName="Test Table 2" class="table table-bordered">
       <thead>
          <tr class="noExl">
             <th>Not Geting exported</th>
             <th>no getting  exported either</th>
          </tr>
          <tr>
             <th>Name(as Header)</th>
             <th>Country(as header)</th>
          </tr>
       </thead>
       <tbody>
          <tr>
             <td>Benjamin Hammond</td>
             <td>United States</td>
          </tr>
          <tr>
             <td>Vikas Lalwani</td>
             <td>India</td>
          </tr>
          <tr>
             <td>Martin Mathews</td>
             <td>France</td>
          </tr>
         <tr>
             <td>Geoffry Schidner</td>
             <td>England</td>
          </tr>
       </tbody>
       <tfoot>
          <tr>
             <td colspan="2">This footer spans 2 cells</td>
          </tr>
       </tfoot>
    </table>
    
    
    <div class="row">
       <div class="col-md-2">
          <a class="btn btn-default" id="exportNow">Export</a>
       </div>
       <div class="col-md-10"></div>
    </div>

    Now we just need to initialize & call plugin to export data to excel on button click

    jQuery(document).ready(function() {
        
        $('#exportNow').on('click', function(e){
            e.preventDefault();
            ResultsToTable();
        });
        
        function ResultsToTable(){    
            $("#resultsTable").table2excel({
                exclude: ".noExl", //this class data should not be excluded in excel
                filename: "Results"
            });
        }
    });

    Executing the above script with HTML data gives output as below, here is the working fiddle

    export-html-table-to-excel-using-jquery-min.png

    That’s it, we are done, hope it helps you.

    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>
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>How To Export Data From Html Table To Excel Use JavaScript</title>
      
      <style>
          /* 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;
          }
      </style>
      
      </head>
      <body>
      
      <div>
      
      <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>
          <tr>
              <!-- 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>
          <tr>
              <th>Physics</th>
              <th>Mathematics</th>
              <th>Chemistry</th>
          </tr>
          <tr>
              <td>1</td>
              <td>2021001</td>
              <td>Jerry</td>
              <td>Male</td>
              <td>18</td>
              <td>100</td>
              <td>99</td>
              <td>98</td>
          </tr>
          <tr>
              <td>2</td>
              <td>2021002</td>
              <td>Tom</td>
              <td>Male</td>
              <td>19</td>
              <td>80</td>
              <td>80</td>
              <td>60</td>
          </tr>
           <tr style='display:none'>
              <td>3</td>
              <td>2021002</td>
              <td>Mickey</td>
              <td>Female</td>
              <td>18</td>
              <td>96</td>
              <td>99</td>
              <td>100</td>
          </tr>
      </table>
      
      <script>
          // 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/vnd.ms-excel" });
          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.
          a.download = "student-record.xls";
      </script>
      
      </body>
      </html>

    Понравилась статья? Поделить с друзьями:
  • Export from wordpress to excel
  • Export from word to excel
  • Export from text to excel
  • Export from python to excel
  • Export from powershell to excel