15

I have a question about exporting an HTML table as an xlsx file. I did some work and now I can export it as an xls, but I need to export it as an xlsx.

Here is my jsFiddle: https://jsfiddle.net/272406sv/1/

Here is my HTML:

<table id="toExcel" class="uitable">
  <thead>
    <tr>
      <th>Kampanya Basligi</th>
      <th>Kampanya Türü</th>
      <th>Kampanya Baslangiç</th>
      <th>Kampanya Bitis</th>
      <th style="text-align: center">Aksiyonlar</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="Item in campaign.campaignList">
      <td> Item.CampaignTitle </td>
      <td> Item.CampaignHotelType </td>
      <td> Item.CampaignHotelCheckInDate) </td>
      <td>Item.CampaignHotelCheckOutDate</td>
      <td style="text-align: center">
        <button> Some Action </button>
      </td>
    </tr>
  </tbody>
</table>

<button onclick="exceller()">EXCEL</button>

Here is my JavaScript code:

<script>
  function exceller() {
    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]--></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];
        })
      }
    var toExcel = document.getElementById("toExcel").innerHTML;
    var ctx = {
      worksheet: name || '',
      table: toExcel
    };
    var link = document.createElement("a");
    link.download = "export.xls";
    link.href = uri + base64(format(template, ctx))
    link.click();
  }
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Erdeniz Korkmaz
  • 303
  • 1
  • 5
  • 11
  • You can check below JSFiddle which converts html table to xlsx, csv and txt format along with custom filename. Link: [JSFiddle](https://jsfiddle.net/foodiepanda/t6w2umcL/) – foodiepanda Jun 09 '20 at 11:27

5 Answers5

17

A great client-side tool for exporting html tables to xlsx, xls, csv, or txt is TableExport by clarketm (me). It is a simple, easy-to-implement, full-featured library with a bunch of configurable properties and methods.

Install

$ npm install tableexport

Usage

TableExport(document.getElementsByTagName("table"));

// OR using jQuery

$("table").tableExport(); 

Documentation

Sample apps to get you started

Check out the compendious docs or just head over to TableExport on Github for a full list of features.

Travis Clarke
  • 5,951
  • 6
  • 29
  • 36
  • 2
    Unfortunately, it doesn't seem to handle formatted (i.e., styled, CSS, etc.) data. The export is a plain, unformatted XLSX file. See also: https://github.com/clarketm/TableExport/issues/125 – Grid Trekkor May 22 '18 at 18:53
  • 1
    @GridTrekkor – TableExport never claims to be able to map CSS styles to XLSX sheet formatting. It was built explicitly to parse complex HTML table data in a robust, controlled manner and allow it to be exported to various file formats (e.g. TXT, CSV, XLS, XLSX) all on the client-side. – Travis Clarke Dec 01 '18 at 03:26
  • How to use this in dot net MVC application? – user2514925 Jun 26 '19 at 07:19
  • @TravisClarke are your plugin able to export from inherited json (a API called) to excel? either xlsx or xls or csv? – mastersuse Apr 03 '20 at 04:02
  • 1
    Is this updated/maintained? – S. Dre May 23 '22 at 08:59
7

You can use this plug-in for exporting table to .xlsx

http://sheetjs.com/demos/table.html

L..
  • 307
  • 1
  • 3
  • 8
4

Take a look at tableExport.jquery.plugin or tableexport.jquery.plugin

Code example

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>HTML table Export</title>  
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="../lib/js-xlsx/xlsx.core.min.js"></script>
    <script type="text/javascript" src="../lib/FileSaver/FileSaver.min.js"></script> 
    <script type="text/javascript" src="../lib/html2canvas/html2canvas.min.js"></script>
    <script type="text/javascript" src="../tableExport.js"></script>
    <script type="text/javaScript">         
        var sFileName = 'ngophi';
        function ExportXLSX(){
            $('#Event').tableExport({fileName: sFileName,
                        type: 'xlsx'
                       });
        }
    </script>
 <style type="text/css">
     body {
        font-size: 12pt;
        font-family: Calibri;
        padding : 10px;
    }
    table {
        border: 1px solid black;
    }
    th {
        border: 1px solid black;
        padding: 5px;
        background-color:grey;
        color: white;
    }
    td {
        border: 1px solid black;
        padding: 5px;
    }
    input {
        font-size: 12pt;
        font-family: Calibri;
    }
 </style>
</head>
<body>  
<a href="#" onClick="ExportXLSX();">DownloadXLSX</a> 
<br/>
<br/>
<div id="Event">
    <table>
        <tr>
            <th>Column One</th>
            <th>Column Two</th>
            <th>Column Three</th>
        </tr>
        <tr>
            <td>row1 Col1</td>
            <td>row1 Col2</td>
            <td>row1 Col3</td>
        </tr>
        <tr>
            <td>row2 Col1</td>
            <td>row2 Col2</td>
            <td>row2 Col3</td>
        </tr>
        <tr>
            <td>row3 Col1</td>
            <td>row3 Col2</td>
            <td><a href="http://www.jquery2dotnet.com/">http://www.jquery2dotnet.com/</a>
            </td>
        </tr>
    </table>
</div>
</body>
</html>
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Mr.Ngo
  • 51
  • 3
2

You won't be able to export it as XLSX without going back to the server. A XLSX file is a collection of XML files, zipped together. This means you do need to create multiple files. This is impossible to do with JS, client-side.

Instead, you should create a function retrieving the data from your HTML table and send that to you server. The server can then create the XLSX file for you (there are a bunch of libs available for that!) and send it back to the client for download.

If you expect to have a huge dataset, the XLSX creation on the server should be done as an async process, where you notify the user when it's done (instead of having the user waiting for the file to be created).

Let us know which language you use on your server, and we'll be able to recommend you some good libraries.

Adrien
  • 1,929
  • 1
  • 13
  • 23
  • Thank you for your help. I did some research and you're right. I'm using angularJS for my frontend things and nodejs for backend. – Erdeniz Korkmaz May 30 '16 at 05:49
  • Then take a look at https://github.com/SheetJS/js-xlsx. This is probably the most popular library to work with XLSX in Node – Adrien May 30 '16 at 06:08
  • 4
    @ErdenizKorkmaz – Historically speaking ... this `"would be"` correct. With all modern browsers, even many legacy browsers, this is quite easy to handle, although I wouldn't recommend it for large sets of data (due to performance reasons). Check out the library I wrote: clarketm/[`TableExport`](https://github.com/clarketm/TableExport); it leverages SheetJS/[`js-xlsx`](https://github.com/SheetJS/js-xlsx) behind the scenes to handle the parsing. – Travis Clarke Jun 03 '17 at 01:12
  • kindly explain this : https://datatables.net/extensions/buttons/examples/initialisation/export – Nilaksha Perera Aug 04 '22 at 08:35
2

I have actually found a solution to this issue and works on client side with javascript and a library from this URL:

https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js

Here is a code sample.

function ExportSkillsToExcel(type, fn, dl)
{
   var elt = document.getElementById('skillsTable');
   var wb = XLSX.utils.table_to_book(elt, { sheet: "skills" });
   return dl ?
     XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }):
     XLSX.writeFile(wb, fn || ('Skills.' + (type || 'xlsx')));
}
Umar Niazi
  • 476
  • 5
  • 14