Save html table as excel

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.

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

    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 of contents

    html-to-xlsx recipe generates Excel xslx files from HTML tables. This isn’t a full HTML -> Excel conversion but a rather pragmatic and fast way to create Excel files from jsreport. The recipe reads input table and extract a couple of CSS style properties using a specific HTML engine (which defaults to chrome), and finally uses the styles to create the Excel cells.

    Examples

    • Basic table
    • Cells with data types
    • Cell with line break
    • Cell with format
    • Cell with formula
    • Merged cells
    • Multiple sheets
    • Conversion JS trigger
    • Insert output into xlsx template
    • Postprocess using xlsx

    The following CSS properties are supported:

    • background-color — cell background color
    • color — cell foreground color
    • border — all the border-[left|right|top|bottom]-width, border-[left|right|top|bottom]-style, border-[left|right|top|bottom]-color will be transformed into Excel cells borders.
    • text-align — text horizontal align in the Excel cell
    • vertical-align — vertical align in the Excel cell
    • width — the Excel column will get the highest width; it can be little bit inaccurate because of pixel to Excel points conversion
    • height — the Excel row will get the highest height
    • font-family — font family, defaults to Calibri
    • font-size — font size, defaults to 16px
    • font-stylenormal, and italic styles are supported
    • font-weight — control whether the cell’s text should be bold or not
    • text-decorationunderline and line-through are supported
    • overflow — the Excel cell will have text wrap enabled if this is set to scroll.

    The following HTML attributes are supported:

    • colspan — numeric value that merges current column with columns to the right
    • rowspan — numeric value that merges current row with rows below.

    Options

    • htmlEngineString (supported values here depends on the HTML engines that you have available in your jsreport installation, by default just chrome is available but you can additionally install better performing cheerio as HTML engine too)
    • waitForJSBoolean whether to wait for the JavaScript trigger to be enabled before trying to read the HTML tables on the page or not. defaults to false.
    • insertToXlsxTemplateBoolean controls if the result of the HTML to Excel tables conversion should be added as new sheets of existing xlsx template, it needs you to set an xlsx template to work. Default is false.

    Sheets

    Each table detected on the HTML source is converted to a new sheet in the final xlsx file. The sheets names are by default Sheet1, Sheet2 etc. However, you can specify a custom sheet name using the name or data-sheet-name attribute on the table element where the data-sheet-name has precedence.

    <table name="Data1">
        <tr>
            <td>1</td>
        </tr>
    </table>
    <table data-sheet-name="Data2">
        <tr>
            <td>2</td>      
        </tr>
    </table>
    

    Cells with data types

    To produce a cell with specific data type you need to use the data-cell-type on the td element. The supported data types are number, boolean, date, datetime and formula:

    <table>
        <tr>
            <td data-cell-type="number">10</td>
            <td data-cell-type="boolean" style="width: 85px">1</td>
            <td data-cell-type="date">2019-01-22</td>
            <td data-cell-type="datetime">2019-01-22T17:31:36.000-05:00</td>
        </tr>
    </table>
    

    Format

    Excel supports setting cell string format. Add the following attributes to the td element:

    • data-cell-format-str -> Specify the raw string format
    • data-cell-format-enum -> Select an existing format

    Possible values of the data-cell-format-enum are:

    • 0 -> format equal to general
    • 1 -> format equal to 0
    • 2 -> format equal to 0.00
    • 3 -> format equal to #,##0
    • 4 -> format equal to #,##0.00
    • 9 -> format equal to 0%
    • 10 -> format equal to 0.00%
    • 11 -> format equal to 0.00e+00
    • 12 -> format equal to # ?/?
    • 13 -> format equal to # ??/??
    • 14 -> format equal to mm-dd-yy
    • 15 -> format equal to d-mmm-yy
    • 16 -> format equal to d-mmm
    • 17 -> format equal to mmm-yy
    • 18 -> format equal to h:mm am/pm
    • 19 -> format equal to h:mm:ss am/pm
    • 20 -> format equal to h:mm
    • 21 -> format equal to h:mm:ss
    • 22 -> format equal to m/d/yy h:mm
    • 37 -> format equal to #,##0 ;(#,##0)
    • 38 -> format equal to #,##0 ;[red](#,##0)
    • 39 -> format equal to #,##0.00;(#,##0.00)
    • 40 -> format equal to #,##0.00;[red](#,##0.00)
    • 41 -> format equal to _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)
    • 42 -> format equal to _("$"* #,##0_);_("$* (#,##0);_("$"* "-"_);_(@_)
    • 43 -> format equal to _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)
    • 44 -> format equal to _("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)
    • 45 -> format equal to mm:ss
    • 46 -> format equal to [h]:mm:ss
    • 47 -> format equal to mmss.0
    • 48 -> format equal to ##0.0e+0
    • 49 -> format equal to @
    <style>
        td {
            width: 60px;
            padding: 5px;
        }
    </style>
    <table>
        <tr>
            <td data-cell-type="number" data-cell-format-str="0.00">10</td>
            <td data-cell-type="number" data-cell-format-enum="3">100000</td>
            <td data-cell-type="date" data-cell-format-str="m/d/yyy">2019-01-22</td>
        </tr>
    </table>
    

    Setting the format is also required when the cell needs to have a specific format category which depends on the computer locale. The cell is otherwise categorized by Excel as General.

    For example, using data-cell-type="date" makes the cell a date and you can use it in the date-based calculations. However, the cell format category in Excel is displayed as General and not Date. To rectify this, you need to use data-cell-format-str to match your locale.

    Formula

    A formula cell can be specified using data-cell-type="formula" on the td element.

    <table>
        <tr>
            <td data-cell-type="number">10</td>
            <td data-cell-type="number">10</td>
            <td data-cell-type="formula">=SUM(A1, B1)</td>
        </tr>
    </table>
    

    Font family

    You can use the following CSS styles to change the default font-family for all cells in table.

    td  { 
      font-family: 'Verdana'; 
      font-size: 18px; 
    }
    

    Insert output into xlsx template

    The table to xlsx conversion can be enough for some cases. However, for more complex cases (like producing pivot tables or complex charts using Excel) there is an option to insert the produced tables into an existing xlsx template (as new sheets) instead of producing a new xlsx file.

    The flow is the following:

    • Open your desktop Excel application and prepare file with pivot tables and charts on the one sheet and with static data on the second.
    • Upload the xlsx to jsreport studio and link it with your html-to-xlsx template generating dynamic table.
    • Make sure the table name matches with the data sheet name in your Excel.

    Running the template now produces dynamic Excel with charts or pivots based on the data assembled by jsreport.

    See this example to get an idea of what can be possible with this feature.

    Conversion triggers

    You may need to postpone conversion of tables until some JavaScript async tasks are processed. If this is the case; set htmlToXlsx.waitForJS = true in the API options or Wait for conversion trigger in the studio menu. When set, the conversion won’t start until you set window.JSREPORT_READY_TO_START = true inside your template’s JavaScript.

    ...
    <script>
        // do some calculations or something async
        setTimeout(function() {
            window.JSREPORT_READY_TO_START = true; //this will start the conversion and read the existing tables on the page
        }, 500);
        ...
    </script>
    

    Issues with row height being larger than actual the content

    When using phantomjs as the engine there are cases when a row height ends with a larger height than the actual content. This is caused by a phantomjs bug that retrieves a larger height when the content of cells contains white space characters.

    There are two possible workarounds:

    • use letter-spacing CSS property with some negative value (demo)
    <!-- without "letter-spacing" the row would be more larger -->
    <table style="letter-spacing: -4px">
        <tr>
            <td> From Date: N/A</td>
            <td> To Date: N/A </td>
            <td> Search Text: N/A </td>
            <td> Sort Order: N/A </td>
            <td> Sort Key: N/A </td>
            <td> Filter: N/A </td>
        </tr>
    </table>
    
    • use line-height: 0 with a specific height (demo)
    <!-- without "line-height" and "height" the row would be more larger -->
    <table style="line-height: 0">
        <tr style="height: 20px">
            <td> From Date: N/A</td>
            <td> To Date: N/A </td>
            <td> Search Text: N/A </td>
            <td> Sort Order: N/A </td>
            <td> Sort Key: N/A </td>
            <td> Filter: N/A </td>
        </tr>
    </table>
    

    Performance

    The chrome engine can have performance problems when evaluating huge tables with many cells. For these cases the recipe provides an additional helper which splits large tables into chunks and runs evaluation in batches. Usage is like each or jsrender for handlebar helpers.

    <table>
        {{#htmlToXlsxEachRows people}}
          <tr>
            <td>{{name}}</td>
            <td>{{address}}</td>
          </tr>
        {{/htmlToXlsxEachRows}}
    </table>
    

    Cheerio HTML engine

    Although the htmlToXlsxEachRows helper prevents Chrome from hanging, the rendering can still be slow. This is because Chrome needs to create DOM elements for the whole table and evaluate every single cell. Fortunately, there is a better option for large tables – using the custom HTML engine cheerio-page-eval.

    This custom engine is experimental and requires manual installation through NPM.

    npm i cheerio-page-eval
    restart jsreport
    

    Afterward, you can select it in the studio HTML to xlsx menu and start using it. This engine doesn’t create DOM representation like Chrome, so it has much better performance. However, the lack of DOM also introduces some limitations.

    • The cheerio engine doesn’t support global CSS styles in the <style> tag. You need to use in-line styles on cells.
    • It also doesn’t evaluate JavaScript in the <script> tags. The helpers and templating engines aren’t limited.

    htmlToXlsxEachRows helper also works with the cheerio engine and can significantly improve rendering memory footprint on long tables.

    Preview in studio

    See general documentation for office preview in studio here.

    Postprocess using xlsx recipe

    The html-to-xlsx will be always limited and you may miss some features that aren’t yet implemented in it. In this case you can use xlsx recipe and postprocess the html-to-xlsx and modify what you need using low level xlsx helpers.

    Demo in playground

    API

    You can specify the template the standard way by using name or shortid, or alternatively you can also send it in the API request. If you have the Excel template stored as an asset you can also reference it in the request.

    {  
      "template":  {  
        "recipe":  "html-to-xlsx",  
        "engine":  "handlebars",  
        "content": "<table></table>",
        "htmlToXlsx":  {  
          "templateAssetShortid":  "xxxx"  
        }  
      },  
      "data":  {}
    }
    

    If you don’t have the xlsx template stored as an asset you can send it directly in the API request.

    {  
      "template":  {  
        "recipe":  "html-to-xlsx",  
        "engine":  "handlebars",  
        "content": "<table></table>",
        "htmlToXlsx":  {  
          "templateAsset":  {  
            "content": "base64 encoded word file",
            "encoding":"base64"
           }
        }  
      },  
      "data":  {}
    }
    

    Время на прочтение
    2 мин

    Количество просмотров 58K

    Введение

    Всем привет! Сегодня я опишу довольно тривиальную, но нигде не освещенную тему экспорта из страницы данных в Excel. На мое удивление сам процесс не описан нигде в полной мере. Итак, приступим.

    Все написано до нас

    Подумал я и начал искать, нашел очень быстро SheetJS , но, боже мой, как там запущено все! Если с форматированием еще можно справиться, то стили — это головная боль.

    Все написано до нас. Подход 2

    В старом-старом SharePoint 2007 есть такая возможность экспортировать эксель файл, на удивление это работает до сих пор и хорошо поддается описанию.

    Что нужно:

    • Современный браузер (проверьте в старых)
    • Отформатированная таблица
    • Colspan, rowspan, border — знание табличной верстки

    var tableToExcel = (function() {
    		var uri = 'data:application/vnd.ms-excel;base64,'
    		, 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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
    		, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    		, format = function(s, c) { 	    	 
    			return s.replace(/{(w+)}/g, function(m, p) { return c[p]; }) 
    		}
    		, downloadURI = function(uri, name) {
    		    var link = document.createElement("a");
    		    link.download = name;
    		    link.href = uri;
    		    link.click();
    		}
    
    		return function(table, name, fileName) {
    			if (!table.nodeType) table = document.getElementById(table)
    				var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    			var resuri = uri + base64(format(template, ctx))
    			downloadURI(resuri, fileName);
    		}
    	})();  

    
        // params: element id, sheet name, file name
        tableToExcel('resultTable','Смета', 'Ремрайон_смета.xls');
    

    Форматирование

    Оформите саму сетку в таблице с помощью атрибутов colspan, rowspan, добавьте стили и после этого вызывайте генерацию файла.

    В заключение

    Могу ответить в комментах на ваши вопросы.

    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

    Понравилась статья? Поделить с друзьями:
  • Save from matlab to excel
  • Save from html to word
  • Save formatting in word
  • Save formatting in excel
  • Save files to pdf from word