简体   繁体   中英

Export content of HTML Table to Excel Sheet so as to be supported by browsers like IE , Mozilla , Firefox etc.?

Here is my HTML Page.

<html>
<head>
<title>Table </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
</script>

</head>
<body>
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

<input id ="export" type = "button" value = "Export"></input>
</body>
</html>

Now i want the user to export the content on web page into excel sheet. How can i do that ? I dont want to go with javascript because in that case the code will be browser - dependent ?

Any Advice ! Thanks in Advance.

PN : I have come across few question in stackoverflow which says use of jQuery can be a good option. But the problem is i have zero knowledge of jQuery .

You can easily use my code to export html file to excel file. In this case, I created your above sample and just copy and paste my code in html file, then you'll see the result and you'll be able to download excel file.

use above java code in first then put this following html code:

<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">
<table class="tableizer-table" id="testTable" summary="Code page support in different versions of MS Windows." rules="groups" 
frame="hsides" border="2">
<tr class="tableizer-firstrow"><th>Header 1</th><th>Header 2</th></tr>
 <tr><td>row 1, cell 1</td><td>row 1, cell 2</td></tr>
 <tr><td>row 2, cell 1</td><td>row 2, cell 2</td></tr>
</table>

use this following java code to export Html to Excel:

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:ExcelWorkbo
ok></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))
  }
})()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM