How to export an HTML table as a .xlsx file
Asked Answered
C

5

18

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>
Catamenia answered 28/5, 2016 at 12:0 Comment(1)
You can check below JSFiddle which converts html table to xlsx, csv and txt format along with custom filename. Link: JSFiddleBukavu
V
3

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.

Valedictory answered 30/5, 2016 at 0:51 Comment(4)
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.Catamenia
Then take a look at github.com/SheetJS/js-xlsx. This is probably the most popular library to work with XLSX in NodeValedictory
@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; it leverages SheetJS/js-xlsx behind the scenes to handle the parsing.Blastocyst
kindly explain this : datatables.net/extensions/buttons/examples/initialisation/…Nabors
B
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.

Blastocyst answered 27/5, 2017 at 0:44 Comment(5)
Unfortunately, it doesn't seem to handle formatted (i.e., styled, CSS, etc.) data. The export is a plain, unformatted XLSX file. See also: github.com/clarketm/TableExport/issues/125Karisakarissa
@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.Blastocyst
How to use this in dot net MVC application?Sergent
@TravisClarke are your plugin able to export from inherited json (a API called) to excel? either xlsx or xls or csv?Coats
Is this updated/maintained?Expression
S
7

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

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

Scission answered 8/8, 2017 at 3:34 Comment(2)
This is the most correct answer. But has problems with Safari, Mac OS and IOSPilgrimage
Anyone know of a ruby gem to do the same on a file? That is, take a downloaded htnl file with the table data in it and convert that to an xlsx (NOT xls)?Farandole
M
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>
Madelle answered 19/4, 2017 at 7:16 Comment(1)
This plugin is simple and good. Works well on xlsx.Icicle
V
3

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.

Valedictory answered 30/5, 2016 at 0:51 Comment(4)
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.Catamenia
Then take a look at github.com/SheetJS/js-xlsx. This is probably the most popular library to work with XLSX in NodeValedictory
@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; it leverages SheetJS/js-xlsx behind the scenes to handle the parsing.Blastocyst
kindly explain this : datatables.net/extensions/buttons/examples/initialisation/…Nabors
K
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/[email protected]/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')));
}
Kiri answered 31/3, 2022 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.