I have a HTML table in velocity template. I want to export the html table data to excel using either java script or jquery, comatibale with all browser.
I am using below script
<script type="text/javascript">
function ExportToExcel(mytblId){
var htmltable= document.getElementById('my-table-id');
var html = htmltable.outerHTML;
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}
</script>
This script works fine in Mozilla Firefox,it pops-up with a dialog box of excel and ask for open or save options. But when I tested same script in Chrome browser it is not working as expected,when clicked on button there is no pop-up for excel. Data gets downloaded in a file with «file type : file» , no extension like .xls
There are no errors in chrome console.
Jsfiddle example :
http://jsfiddle.net/insin/cmewv/
This works fine in mozilla but not in chrome.
Chrome browser Test Case :
First Image:I click on Export to excel button
and result :
asked Mar 11, 2014 at 6:22
2
Excel export script works on IE7+, Firefox and Chrome.
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|</A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|</input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv:11./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
Just create a blank iframe:
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on:
<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
JasonMArcher
14k22 gold badges56 silver badges52 bronze badges
answered Jun 6, 2014 at 11:59
sampopessampopes
2,6161 gold badge21 silver badges33 bronze badges
53
Datatable plugin solves the purpose best and allows us to export the HTML table data into Excel , PDF , TEXT. easily configurable.
Please find the complete example in below datatable reference link :
https://datatables.net/extensions/buttons/examples/html5/simple.html
(screenshot from datatable reference site)
answered Aug 4, 2016 at 7:35
AdityaAditya
2,37517 silver badges25 bronze badges
6
This could help
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 = "YOUR HTML AS TABLE"
var ctx = {
worksheet : 'Worksheet',
table : htmls
}
var link = document.createElement("a");
link.download = "export.xls";
link.href = uri + base64(format(template, ctx));
link.click();
}
answered Jan 8, 2015 at 15:14
todotresdetodotresde
1,7402 gold badges19 silver badges25 bronze badges
2
You can use tableToExcel.js to export table in excel file.
This works in a following way :
1). Include this CDN in your project/file
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>
2). Either Using JavaScript:
<button id="btnExport" onclick="exportReportToExcel(this)">EXPORT REPORT</button>
function exportReportToExcel() {
let table = document.getElementsByTagName("table"); // you can use document.getElementById('tableId') as well by providing id to the table tag
TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
name: `export.xlsx`, // fileName you could use any name
sheet: {
name: 'Sheet 1' // sheetName
}
});
}
3). Or by Using Jquery
<button id="btnExport">EXPORT REPORT</button>
$(document).ready(function(){
$("#btnExport").click(function() {
let table = document.getElementsByTagName("table");
TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
name: `export.xlsx`, // fileName you could use any name
sheet: {
name: 'Sheet 1' // sheetName
}
});
});
});
You may refer to this github link for any other information
https://github.com/linways/table-to-excel/tree/master
or for referring the live example visit the following link
Hope this will help someone
answered Mar 3, 2020 at 16:10
3
Instead of using window.open
you can use a link with the onclick
event.
And you can put the html table into the uri and set the file name to be downloaded.
Live demo :
function exportF(elem) {
var table = document.getElementById("table");
var html = table.outerHTML;
var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url
elem.setAttribute("href", url);
elem.setAttribute("download", "export.xls"); // Choose the file name
return false;
}
<table id="table" border="1">
<tr>
<td>
Foo
</td>
<td>
Bar
</td>
</tr>
</table>
<a id="downloadLink" onclick="exportF(this)">Export to excel</a>
answered Mar 6, 2019 at 12:50
R3tepR3tep
12.3k10 gold badges47 silver badges74 bronze badges
1
TableExport — The simple, easy-to-implement library to export HTML tables to xlsx, xls, csv, and txt files.
To use this library, simple call the TableExport
constructor:
new TableExport(document.getElementsByTagName("table"));
// OR simply
TableExport(document.getElementsByTagName("table"));
// OR using jQuery
$("table").tableExport();
Additional properties can be passed-in to customize the look and feel of your tables, buttons, and exported data. See here more info
answered Jul 28, 2017 at 19:06
insigninsign
5,13538 silver badges33 bronze badges
1
answered Mar 18, 2014 at 7:02
6
My merge of these examples:
https://www.codexworld.com/export-html-table-data-to-excel-using-javascript
https://bl.ocks.org/Flyer53/1de5a78de9c89850999c
function exportTableToExcel(tableId, filename) {
let dataType = 'application/vnd.ms-excel';
let extension = '.xls';
let base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
let 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>';
let render = function(template, content) {
return template.replace(/{(w+)}/g, function(m, p) { return content[p]; });
};
let tableElement = document.getElementById(tableId);
let tableExcel = render(template, {
worksheet: filename,
table: tableElement.innerHTML
});
filename = filename + extension;
if (navigator.msSaveOrOpenBlob)
{
let blob = new Blob(
[ 'ufeff', tableExcel ],
{ type: dataType }
);
navigator.msSaveOrOpenBlob(blob, filename);
} else {
let downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
downloadLink.href = 'data:' + dataType + ';base64,' + base64(tableExcel);
downloadLink.download = filename;
downloadLink.click();
}
}
answered Sep 19, 2019 at 12:41
1
Simplest way using Jquery
Just add this:
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>
Then add Jquery script:
<script type="text/javascript">
$(document).ready(function () {
$("#exportBtn1").click(function(){
TableToExcel.convert(document.getElementById("tab1"), {
name: "Traceability.xlsx",
sheet: {
name: "Sheet1"
}
});
});
});
</script>
Then add HTML button:
<button id="exportBtn1">Export To Excel</button><br><br>
Note: "exportBtn1"
will be button ID and
«tab1» will be table ID
answered Dec 2, 2020 at 18:49
0
Regarding to sampopes answer from Jun 6 ’14 at 11:59:
I have insert a css style with font-size of 20px to display the excel data greater. In sampopes code the leading <tr>
tags are missing, so i first output the headline and than the other tables lines within a loop.
function fnExcelReport()
{
var tab_text = '<table border="1px" style="font-size:20px" ">';
var textRange;
var j = 0;
var tab = document.getElementById('DataTableId'); // id of table
var lines = tab.rows.length;
// the first headline of the table
if (lines > 0) {
tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
}
// table data lines, loop starting from 1
for (j = 1 ; j < lines; j++) {
tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";
}
tab_text = tab_text + "</table>";
tab_text = tab_text.replace(/<A[^>]*>|</A>/g, ""); //remove if u want links in your table
tab_text = tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text = tab_text.replace(/<input[^>]*>|</input>/gi, ""); // reomves input params
// console.log(tab_text); // aktivate so see the result (press F12 in browser)
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
// if Internet Explorer
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv:11./)) {
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, "DataTableExport.xls");
}
else // other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
answered Mar 16, 2016 at 12:54
2
function exportToExcel() {
var tab_text = "<tr bgcolor='#87AFC6'>";
var textRange; var j = 0, rows = '';
tab = document.getElementById('student-detail');
tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";
var tableData = $('#student-detail').DataTable().rows().data();
for (var i = 0; i < tableData.length; i++) {
rows += '<tr>'
+ '<td>' + tableData[i].value1 + '</td>'
+ '<td>' + tableData[i].value2 + '</td>'
+ '<td>' + tableData[i].value3 + '</td>'
+ '<td>' + tableData[i].value4 + '</td>'
+ '<td>' + tableData[i].value5 + '</td>'
+ '<td>' + tableData[i].value6 + '</td>'
+ '<td>' + tableData[i].value7 + '</td>'
+ '<td>' + tableData[i].value8 + '</td>'
+ '<td>' + tableData[i].value9 + '</td>'
+ '<td>' + tableData[i].value10 + '</td>'
+ '</tr>';
}
tab_text += rows;
var data_type = '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 border="2px">{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 ctx = {
worksheet: "Sheet 1" || 'Worksheet',
table: tab_text
}
document.getElementById("dlink").href = data_type + base64(format(template, ctx));
document.getElementById("dlink").download = "StudentDetails.xls";
document.getElementById("dlink").traget = "_blank";
document.getElementById("dlink").click();
}
Here Value 1 to 10 are column names that you are getting
marc_s
726k174 gold badges1326 silver badges1449 bronze badges
answered Jun 6, 2018 at 15:04
RockRock
5246 silver badges14 bronze badges
Below code will work on latest Chrome , Edge , Firefox , not require 3rd party library.
HTML
<button onclick="download_table_as_csv('MyTableID_Value');">Export as CSV</button>
Jscript
function download_table_as_csv(table_id, separator = ',') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(rn|n|r)/gm, '').replace(/(ss)/gm, ' ')
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('n');
// Download it
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}
answered Aug 2, 2022 at 5:09
HO LI PinHO LI Pin
1,35111 silver badges13 bronze badges
My version of @sampopes answer
function exportToExcel(that, id, hasHeader, removeLinks, removeImages, removeInputParams) {
if (that == null || typeof that === 'undefined') {
console.log('Sender is required');
return false;
}
if (!(that instanceof HTMLAnchorElement)) {
console.log('Sender must be an anchor element');
return false;
}
if (id == null || typeof id === 'undefined') {
console.log('Table id is required');
return false;
}
if (hasHeader == null || typeof hasHeader === 'undefined') {
hasHeader = true;
}
if (removeLinks == null || typeof removeLinks === 'undefined') {
removeLinks = true;
}
if (removeImages == null || typeof removeImages === 'undefined') {
removeImages = false;
}
if (removeInputParams == null || typeof removeInputParams === 'undefined') {
removeInputParams = true;
}
var tab_text = "<table border='2px'>";
var textRange;
tab = $(id).get(0);
if (tab == null || typeof tab === 'undefined') {
console.log('Table not found');
return;
}
var j = 0;
if (hasHeader && tab.rows.length > 0) {
var row = tab.rows[0];
tab_text += "<tr bgcolor='#87AFC6'>";
for (var l = 0; l < row.cells.length; l++) {
if ($(tab.rows[0].cells[l]).is(':visible')) {//export visible cols only
tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
}
}
tab_text += "</tr>";
j++;
}
for (; j < tab.rows.length; j++) {
var row = tab.rows[j];
tab_text += "<tr>";
for (var l = 0; l < row.cells.length; l++) {
if ($(tab.rows[j].cells[l]).is(':visible')) {//export visible cols only
tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
}
}
tab_text += "</tr>";
}
tab_text = tab_text + "</table>";
if (removeLinks)
tab_text = tab_text.replace(/<A[^>]*>|</A>/g, "");
if (removeImages)
tab_text = tab_text.replace(/<img[^>]*>/gi, "");
if (removeInputParams)
tab_text = tab_text.replace(/<input[^>]*>|</input>/gi, "");
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv:11./)) // If Internet Explorer
{
myIframe.document.open("txt/html", "replace");
myIframe.document.write(tab_text);
myIframe.document.close();
myIframe.focus();
sa = myIframe.document.execCommand("SaveAs", true, document.title + ".xls");
return true;
}
else {
//other browser tested on IE 11
var result = "data:application/vnd.ms-excel," + encodeURIComponent(tab_text);
that.href = result;
that.download = document.title + ".xls";
return true;
}
}
Requires an iframe
<iframe id="myIframe" style="opacity: 0; width: 100%; height: 0px;" seamless="seamless"></iframe>
Usage
$("#btnExportToExcel").click(function () {
exportToExcel(this, '#mytable');
});
answered Oct 26, 2018 at 10:34
irfandarirfandar
1,67023 silver badges24 bronze badges
Very Easy Code
Follow this instruction
Create excel.php file in your localhost root directory and copy and past this code.
Like this
http://localhost/excel.php?fileName=excelfile&link=1
<!-- http://localhost/excel.php?fileName=excelfile&link=2 -->
<!DOCTYPE html>
<html>
<head>
<title>Export excel file from html table</title>
</head>
<body style="display:
<?php
if( $_REQUEST['link'] == 1 ){
echo 'none';
}
?>;
">
<!-- --------Optional-------- -->
Excel <input type="radio" value="1" name="exportFile">
Others <input type="radio" value="2" name="exportFile">
<button onclick="myFunction()">Download</button>
<br>
<br>
<!-- --------/Optional-------- -->
<table width="100%" id="tblData">
<tbody>
<tr>
<th>Student Name</th>
<th>Group</th>
<th>Roll No.</th>
<th>Class</th>
<th>Contact No</th>
</tr>
<tr>
<td>Bulbul Sarker</td>
<td>Science</td>
<td>1</td>
<td>Nine</td>
<td>01724....</td>
</tr>
<tr>
<td>Karim</td>
<td>Science</td>
<td>3</td>
<td>Nine</td>
<td>0172444...</td>
</tr>
</tbody>
</table>
</body>
</html>
<style>
table#tblData{
border-collapse: collapse;
}
#tblData th,
#tblData td{
border:1px solid #CCC;
text-align: center;
}
</style>
<script type="text/javascript">
/*--------Optional--------*/
function myFunction() {
let val = document.querySelector('input[name="exportFile"]:checked').value;
if(val == 1)
{
this.exportTableToExcel();
}
}
/*--------/Optional--------*/
function exportTableToExcel(){
let filename2 = "<?php echo $_REQUEST['fileName']; ?>";
let tableId = 'tblData';
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableId);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
let filename = filename2?filename2+'.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();
}
}
</script>
<?php
if( $_REQUEST['link'] == 1 ){
echo '<script type="text/javascript">
exportTableToExcel();
</script>';
}
?>
answered Nov 24, 2020 at 7:32
Html
<a onclick="download_to_excel()">Download</a>
<table id="tableId">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3">Data Not Found</td>
</tr>
</tbody>
</table>
JavaScript
function download_to_excel()
{
var tab_text="<table><tr>";
var textRange = '';
var j=0;
var tab = document.getElementById('tableId'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text += tab.rows[j].innerHTML+"</tr>";
}
tab_text +="</table>";
var a = document.createElement('a');
var data_type = 'data:application/vnd.ms-excel';
a.href = data_type + ', ' + encodeURIComponent(tab_text);
//setting the file name
a.download = 'file_name.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
}
answered Oct 27, 2021 at 6:32
Время на прочтение
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, добавьте стили и после этого вызывайте генерацию файла.
В заключение
Могу ответить в комментах на ваши вопросы.
We can use window.open() to export table data into Excel or any required format. It is the easiest and simplest way of creating a file with data without server side trip. window.open() requires 2 input parameters for this-
- the required MIMEtype and
- element that contains our data table.
If you want to export your Gridview data, then place that Gridview inside a container (like DIV etc.) and supply the DIV to winodw.open(). Also, be noted that window.open() has its scope and limitations in terms of browser vendors and customizing output file name.
Recently, I got a thread on Microsoft’s asp.net forum regarding exporting GridView/table/div data into MS Excel at client side. You can refer that link — http://forums.asp.net/t/1854204.aspx/1?Export+to+Excel
So, I decided to write this post in context of helping other needy toubleshooters.
This is the second version you are reading as first was to help a forum user only. You know GridView gets rendered into «table» format. So, if you are using asp.net and looking for your GridView then keep your GridView inside a div element to make it easy.
If you are just looking for code snippet that do magic job for our Excel-export then it is single line code as below —
window.open('data:application/vnd.ms-excel,' + $('div[id$=divTableDataHolder]').html());
Understanding how it works:
To export our table data, we are going to use window.open(). I know most of you would be definitely familiar with this version of the window.open()-
window.open(URL, name , specs , replace )
But here you will see its another version :
window.open(MIMEtype, dataContainerItem)
window.open (MIMEtype , replace ) //replace=> dataContainerItem
| |________ It takes the element from window opener
|___________ Default MIME type is «text/html«
We have to just specify our required MIMEtype and it does the job for us! So for converting into MS Excel, we will specify data:application/vnd.ms-excel as MIME type.
Replace is the item taken from opener-window whose html we are going to send into Excel sheet. This container element shouldn’t have special characters. If it contains then we have to encode those characters using JavaScript’s encodeURIComponent(). For more details on encodeURIComponent() refer — http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp
So we will create a simple html table inside a div as —
<button id="myButtonControlID">Export Table data into Excel</button> <div id="divTableDataHolder"> <table> <tr><th>ColumnOne </th><th>ColumnTwo</th></tr> <tr> <td>row1ColValue1</td><td>row1ColValue2</td> </tr> <tr> <td>row2ColValue1</td><td>row2ColValue2</td> </tr> </table> </div>
Now, we will write our magic jQuery/JavaScript code to get done our job. In this snippet I am using encodeURIComponent() to handle special characters. You can use without it also as I have mentioned in top of this post.
$("[id$=myButtonControlID]").click(function(e) { window.open('data:application/vnd.ms-excel,' + encodeURIComponent( $('div[id$=divTableDataHolder]').html())); e.preventDefault(); });
I am giving you the ready-reference snippet that contains a single line of code window.open() to export table data into MS excel
You can get more details on jQuery website: http://forum.jquery.com/topic/anyway-to-export-html-table-to-excel
Blog Extended On: 21-July-2013
window.open() has its scope and limitations(ex IE not working & filename) that has been well explained in this post: Export to CSV using jQuery and html
In terms of huge data export, I have already tested with 2500 rows and it works fine and I am sure it will work for more than this figure also. You can see it live : http://jsfiddle.net/AnilAwadh/wJyWm/
Simple Code |
<script type=»text/javascript»> function ExportToExcel(mytblId) { var var // MS OFFICE 2003 : // MS OFFICE 2007 : window.open(‘data:application/vnd.ms-excel,’ } </script> |
We can Customize our table data on the fly
using custom Export Function
Customize function to Export Data |
<script type=»text/javascript»> function CustomMethodToExport(tblId) { var var var numofRows = gTable.rows.length-1; var var numofCells = gTable.rows[0].cells.length-1 ; for ( { var var for { var var var if(tempstr.search(«%») > 0) { if(tempstr.search(‘-‘) >= 0) { color = «red»; } else { color = «green»; } } else { color = «black»; } tdhtml = tdhtml + «<td style=’text-align:right;color:»+ } trhtml = trhtml + «<tr>» + tdhtml + «</tr>»; } html = «<table // MS OFFICE 2003 : // MS OFFICE 2007 : window.open(‘data:application/vnd.ms-excel,’ } </script> |
Export Data Using Jquery |
$(window).load(function(){ $(«#clickToExcel«).click(function() { var dtltbl = $(‘#mytbl’).html(); window.open(‘data:application/vnd.ms-excel,’ + $(‘# mytbl’).html()); }); });//]]> |
HTML Body Code |
<body> <form id=»form1″ runat=»server»> <div> <table id=»mytbl» border=»1″> <tr> <td> <b>ID</b></td> <td> <b>Name</b></td> <td> <b>Profit/Loss</b></td> </tr> <tr> <td> 1</td> <td> Tarun</td> <td> 200%</td> </tr> <tr> <td> 2</td> <td> Ajay</td> <td> -200%</td> </tr> </table> <a id=»clickToExcel» href=»javascript:ExportToExcel(‘mytbl’)»>Export Custome Export</a> </div> </form> </body> |
Note:
If you have special character problem then write down following
code before Window.open method inside script function
while (html.indexOf('á') != -1) html = html.replace('á', 'á');
while (html.indexOf('é') != -1) html = html.replace('é', 'é');
while (html.indexOf('í') != -1) html = html.replace('í', 'í');
while (html.indexOf('ó') != -1) html = html.replace('ó', 'ó');
while (html.indexOf('ú') != -1) html = html.replace('ú', 'ú');
while (html.indexOf('º') != -1) html = html.replace('º', 'º');
Use MIME
Type for MS Office 2003
application/vnd.ms-excel
Use MIME
Type for MS Office 2007 :
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
12.03.2013, 14:53 |
||||
|
||||
Проблема с кодировками при экспорте талицы в Excel Здравствуйте! Имееся такая штука: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <h2>Заявка на смену пароля:</h2> <table id="123" width="65%" style="border-collapse: collapse; border: 1px solid #FF0077;"> <tr><td> Для смены пароля обращяться: </td> <td> Туда и сюда.... </td> </tr> </table> <script> var table= document.getElementById("123"); var html = table.outerHTML; window.open('data:application/vnd.ms-excel; UNICODE,' + encodeURIComponent(html)); </script> </body> </html> Сохранение динамической табличики у клиента в *.xls файлик с диалогом. Все прекрасно работает, но проблема с кодировкой — русский текст закорючками. Актив Х мен я не устраивет никакким местом, мне достаточно этого диалога, что нужно запихать еще при создании окна в window.open('data:application/vnd.ms-excel; UTF-8,' + encodeURIComponent(html)); ,чтоб ы все было нормально? Спасибо!
|
12.03.2013, 17:49 |
||||
|
||||
Видимо Excel не переваривает UTF-8. |
12.03.2013, 19:35 |
||||
|
||||
Странно, если пересохраниьт готовый файлик в блокноте с кодировкой utf8, то все нормально. А сохраняет эксель не в хлс, в какой-то хмл, но это другой вопрос, меня устроит, что угодно, лишь бы табличка с миниимальными стиялми, как на страничке. Просто, куда бы еще присунуть упоминание о кодировке в момент открытия новой страницы? |
13.03.2013, 04:01 |
||||||||||||
|
||||||||||||
Родной формат — xlsx/xls, это бинарные форматы.
Он и так в utf-8, просто без BOM-метки. Значит нужно ставить ее:
Нафига тут UTF-8 втыкнуто ? |
13.03.2013, 04:19 |
||||||||
|
||||||||
Не, не выкинуто, просто в этой версии не проставлено, я че туда только не ставил и утф и цп1251 и всякую другую нечисть. А так, 'data:application/vnd.ms-excel,' + 'uFEFF' + encodeURIComponent(html) , заинтриовало, щас приду на работу попробую
Вот меня и напрягло, когда я открылвы ходящий xls файлик блокнотом, а там тэговая структура по типу rtf или xml. |
13.03.2013, 07:03 |
||||
|
||||
C uFEFF заработало. Кодировку эксель стал расчухивать и кракозябры ушли. Теперь осталось решить вопрос формирования нормального *.xls/ Спасибо огромное за помощь |
03.02.2015, 13:06 |
|||
|
|||
Спасибо помогло! Спасибо помогло! |