Skip to content

Instantly share code, notes, and snippets.

@insin
Last active October 29, 2024 01:21
Show Gist options
  • Select an option

  • Save insin/1031969 to your computer and use it in GitHub Desktop.

Select an option

Save insin/1031969 to your computer and use it in GitHub Desktop.
Export a <table> to Excel - http://bl.ocks.org/insin/1031969
<!DOCTYPE html>
<html>
<head>
<title>tableToExcel Demo</title>
<script src="tableToExcel.js"></script>
</head>
<body>
<h1>tableToExcel Demo</h1>
<p>Exporting the W3C Example Table</p>
<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">
<table id="testTable" summary="Code page support in different versions of MS Windows." rules="groups" frame="hsides" border="2"><caption>CODE-PAGE SUPPORT IN MICROSOFT WINDOWS</caption><colgroup align="center"></colgroup><colgroup align="left"></colgroup><colgroup span="2" align="center"></colgroup><colgroup span="3" align="center"></colgroup><thead valign="top"><tr><th>Code-Page<br>ID</th><th>Name</th><th>ACP</th><th>OEMCP</th><th>Windows<br>NT 3.1</th><th>Windows<br>NT 3.51</th><th>Windows<br>95</th></tr></thead><tbody><tr><td>1200</td><td style="background-color: #00f; color: #fff">Unicode (BMP of ISO/IEC-10646)</td><td></td><td></td><td>X</td><td>X</td><td>*</td></tr><tr><td>1250</td><td style="font-weight: bold">Windows 3.1 Eastern European</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1251</td><td>Windows 3.1 Cyrillic</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1252</td><td>Windows 3.1 US (ANSI)</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1253</td><td>Windows 3.1 Greek</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1254</td><td>Windows 3.1 Turkish</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1255</td><td>Hebrew</td><td>X</td><td></td><td></td><td></td><td>X</td></tr><tr><td>1256</td><td>Arabic</td><td>X</td><td></td><td></td><td></td><td>X</td></tr><tr><td>1257</td><td>Baltic</td><td>X</td><td></td><td></td><td></td><td>X</td></tr><tr><td>1361</td><td>Korean (Johab)</td><td>X</td><td></td><td></td><td>**</td><td>X</td></tr></tbody><tbody><tr><td>437</td><td>MS-DOS United States</td><td></td><td>X</td><td>X</td><td>X</td><td>X</td></tr><tr><td>708</td><td>Arabic (ASMO 708)</td><td></td><td>X</td><td></td><td></td><td>X</td></tr><tr><td>709</td><td>Arabic (ASMO 449+, BCON V4)</td><td></td><td>X</td><td></td><td></td><td>X</td></tr><tr><td>710</td><td>Arabic (Transparent Arabic)</td><td></td><td>X</td><td></td><td></td><td>X</td></tr><tr><td>720</td><td>Arabic (Transparent ASMO)</td><td></td><td>X</td><td></td><td></td><td>X</td></tr></tbody></table>
</body>
</html>
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]--></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]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
@sathinduga

Copy link
Copy Markdown

How can we set the file name, that's downloading..?

@JCarlosR

JCarlosR commented May 6, 2016

Copy link
Copy Markdown

@pepitos did you find an answer?

@Blaskyy

Blaskyy commented May 11, 2016

Copy link
Copy Markdown

didn't work on large table

@Limky

Limky commented May 23, 2016

Copy link
Copy Markdown

If you want Hangul(Korea language) processing
Add td tag next example Write &nbsp; ....front (String you write) td tag and add "META HTTP-EQUIVE="CONTENT-TYPE" CONTENT="TEXT/HTML; CHARSET=KSC5601" " in head tag

@abrilgzz

Copy link
Copy Markdown

This does not seem to be working in Safari. Any ideas?

@estalisto

Copy link
Copy Markdown

Alguien que me ayude urgente, he puesto este código en mi html y funciona de maravilla, pero tiene un ligero problema con las tildes... quien ha podido arreglar esa parteURGENTE???

@estalisto

estalisto commented Mar 22, 2017

Copy link
Copy Markdown

para los interesados en arreglar el UTF-8, aquí les dejo..

var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '

{table}
'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()

@jbmonroe

jbmonroe commented Jun 14, 2017

Copy link
Copy Markdown

Antes de </head> en la cadena de la plantilla, inserte <meta charset = "utf-8">.

Esto obliga a Excel a interpretar los personajes como usted espera.

@alejandroiron

alejandroiron commented Jul 12, 2017

Copy link
Copy Markdown

Funciona:
"Antes de en la cadena de la plantilla, inserte .<meta charset = "utf-8">"
Gracias.

@sandrady

Copy link
Copy Markdown

can anyone help me?? I need to export 3 tables in one page at a time. thanks in advance.
image

@DiegoA15

Copy link
Copy Markdown

ola disculpa quiero generar un reporte con datos ordenados por fechas que con la ayuda de tu gist pude lograr pero necesito que la información me la acomode en distintas hojas según el día que se realizo dicha actividad, a lo q m refiero es q tengo una tabla de 100 datos y q 50 son de ayer y los otros 50 de hoy osea q me baje el libro con 2 hojas una con la información de ayer y la otra con la de hoy

@iespino00

Copy link
Copy Markdown

Someone knows how to save the file with a default name?

@Bill-VA

Bill-VA commented Nov 21, 2017

Copy link
Copy Markdown

This works well as long as there's not a lot of data. I'm trying to export a table with a couple thousand rows and it causes the browser to bomb and display the dreaded about:blank page. Bummer, now I have to find another way to export my table.

@tamarfi

tamarfi commented Dec 25, 2017

Copy link
Copy Markdown

I want to export the excel from right to left
How can i do it?
I add dir="rtl" it didn't help

@tamarfi

tamarfi commented Dec 26, 2017

Copy link
Copy Markdown

I found the result how to export the excel from right to left:
add this-<x:DisplayRightToLeft/> in the <x:WorksheetOptions> tag like this

@tamarfi

tamarfi commented Dec 26, 2017

Copy link
Copy Markdown

When i want to save the excel i get this message:
2017-12-26_1415

Someone can help me to solve it?

@vnaikregcorp

Copy link
Copy Markdown

var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '

{table}
'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()

Above function works fine for me. I have hyperlinks in my table. How do I remove those hyperlinks ?

@Harsha-0202

Copy link
Copy Markdown

Above function works fine for me. table include input tags how to hide the input tags

@crafcre

crafcre commented Sep 27, 2018

Copy link
Copy Markdown

How do I export to OpenOffice?

@http-droguett

Copy link
Copy Markdown

Could someone change the name when doing the download?

@yuvigaur

yuvigaur commented Apr 9, 2019

Copy link
Copy Markdown

how to save file with my given name , how to change name while save
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '

{table}
'+sessionStorage.getItem("sellerInfo")+'
GSTIN : '+sessionStorage.getItem("GSTNumber")+'State Code : '+sessionStorage.getItem("stateCodeNumber")+'
Invoice NoInvoice DateBuyer NameBuyer GSTBuyer StateInvoice AmountTax
'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: "test" || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
/// please change name while save
}
})()

@phanchanra

Copy link
Copy Markdown

I export on ubuntu It do not know extension

@shizukura06

Copy link
Copy Markdown

It works great on Excel in Windows, but when exporting it in Mac Excel, the gridlines won't show up

@vijayintelli72

Copy link
Copy Markdown

integer value shows as scientific number, how to slove that?

@valentincognito

valentincognito commented Apr 10, 2020

Copy link
Copy Markdown

For encoding problems, add the following in the template string:

<meta charset="utf-8"></meta>

Like this:

let uri = 'data:application/vnd.ms-excel;charset=utf-8;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><meta charset="utf-8"></meta><!--[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]; }) }

@JeanPadVill

Copy link
Copy Markdown

Can anyone tell me how can i give the default name to the files when i download?

@DinosMpo

DinosMpo commented Apr 8, 2021

Copy link
Copy Markdown

For encoding problems, add the following in the template string:

<meta charset="utf-8"></meta>

Like this:

let uri = 'data:application/vnd.ms-excel;charset=utf-8;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><meta charset="utf-8"></meta><!--[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]; }) }

Thank you

@Zengry10

Zengry10 commented Feb 8, 2024

Copy link
Copy Markdown

to change the default value of the download file :

var tableToExcel = (function() {
  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]; }); };
  
  return function(table, filename, name) {
    if (!table.nodeType) table = document.getElementById(table);
    if (!table) {
      console.error("Table element with provided ID not found.");
      return;
    }
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
    var downloadLink = document.createElement("a");
    downloadLink.href = uri + base64(format(template, ctx));
    downloadLink.download = filename || 'export.xls';
    downloadLink.click();
  };
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment