How to use this HTML table to excel function in jquery / javascript - javascript

this is the fiddle
https://jsfiddle.net/shaswatatripathy/ym4egje0/7/
How to use the tableToExcel function and make it work in Internet Explorer 11
Also It should work in Google chrome thats better .
Cant use any Iframe
Objective
Have to export table to excel file for IE and after much searching found this function from
Generate excel sheet from html tables using jquery
but not able to use it .
HTML
<input id="btnExport" type="button" value = "Generate File" />
<table id="table">
<th>
<tr>
<td>coulmn1</td>
<td>column2</td>
</tr>
</th>
<tbody>
<tr>
<td>row1column1</td>
<td>row1column2</td>
</tr>
</tbody>
</table>
JS
$("#btnExport").click(function (e) {
TableToExcel;
});
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 cellspacing="0" rules="rows" border="1" style="color:Black;background-color:White;border-color:#CCCCCC;border-width:1px;border-style:None;width:100%;border-collapse:collapse;font-size:9pt;text-align:center;">{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 }
if (navigator.msSaveBlob) {
var blob = new Blob([format(template, ctx)], { type: 'application/vnd.ms-excel', endings: 'native' });
navigator.msSaveBlob(blob, 'export.xls')
} else {
window.location.href = uri + base64(format(template, ctx))
}
}
})()

Related

How to Show Image in a simple grid not web grid from database. Image saved in byte array format

I am using ASP.NET MVC 4.0 and I am trying to show the image in a simple grid, but the grid appears blank. The image is saved in byte array format. I am getting the other column details but not the image.
Below is the complete controller code for saving the image in byte array format and displaying from database:-
public ActionResult Index()
{
return View();
}
public ActionResult Savedata(HttpPostedFileBase Image)
{
SaveImage obj = new SaveImage();
string result;
if (Image != null)
{
HttpPostedFileBase httpobj = Request.Files["Image"];
string[] Imagename = httpobj.FileName.Split('.');
obj.ImageName=Imagename[0];
using (Stream inputStream = Request.Files[0].InputStream) //File Stream which is Uploaded
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
obj.ImagePic = memoryStream.ToArray();
}
var path = Path.GetFileNameWithoutExtension(Image.FileName) + DateTime.Now.ToString("ddMMyyhhmmss") + Path.GetExtension(Image.FileName);
result = path.Replace(" ", string.Empty);
var serversavepath = Path.Combine(Server.MapPath("~/DemoImages/") + result);
Image.SaveAs(serversavepath);
obj.ImageName= result;
entity.SaveImages.Add(obj);
entity.SaveChanges();
}
//return View("Index");
return Content("<script>alert('Data Successfully Submitted');location.href='../Home/Index';</script>");
}
public JsonResult BindGrid()
{
DataRow[] result;
var output = (from c in entity.SaveImages.AsEnumerable()
select new
{
ID = c.Id,
ImageName = c.ImageName,
//ImagePic = c.ImagePic,
ImagePic = Convert.ToBase64String(c.ImagePic)
}).ToList();
var data = new { result = output };
return Json(output, JsonRequestBehavior.AllowGet);
}
Here is my complete View code. I am using a single view.
<script type="text/javascript">
$(function () {
$.post("#Url.Content("~/Home/BindGrid")", null, function (data) { bindgrid(data); }, "Json");
});
</script>
<script type="text/javascript">
$(function save() {
debugger;
$("#btnSave").click(function () {
location.href = '#Url.Action("Savedata", "Home")';
});
});
function bindgrid(data) {
var body = "";
$("#Grid tbody").empty();
$.each(data.result, function (key, value) {
body += "<tr><td> " + value.ID + "</td>" +
"<td>" + value.ImageName + "</td>" +
"<td>" + value.ImagePic + "</td>" +
"<td> <a style='cursor:pointer' onclick=Edit(" + value.Id + ");>Edit</a> <a style='cursor:pointer' onclick=Delete(" + value.Id + ");>Delete</a></td></tr>";
});
$("#Grid tbody").append(body);
}
</script>
<div>
#using (Html.BeginForm("Savedata", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<table>
<tr>
<td>
Upload Image
</td>
<td><input type="file" name="Image" id="Image" style="width:100%" /></td>
</tr>
</table>
</div>
<br/>
<div>
<input type="submit" value="save" id="btnSave" />
</div>
}
<div id="list" style="width: 997px; margin-right: 0px;">
<table id="Grid">
<thead>
<tr>
<th>
ID
</th>
<th>
IMAGE NAME
</th>
<th>
IMAGES
</th>
<th>
ACTION
</th>
</tr>
</thead>
<tbody>
#foreach (var item in entity.SaveImages)
{
<tr>
<td>#item.Id</td>
<td>#item.ImageName</td>
<td><img src="~/DemoImages/#item.ImagePic" width="100" height="100" /></td>
#*<td><img src="string.format("data:image/png;base64 {0}",base64data)"/></td>*#
</tr>
}
</tbody>
</table>
</div>
</div>
</body>
I want the grid to display the images with other column details.
Your server-side code seems a little bit confused. I don't know if this is the result of misunderstanding, or multiple different attempts to make it work, or what. But the thing which stands out is that you are saving the image both to the server's disk and to the database. I can't see a reason to do both. Normally it's more efficient to save the file directly to disk, and just write the path and filename to the database, so the file can be located later.
P.S. Also I can't understand why you sometimes used Request.Files["Image"]; when the file is already available via the Image variable. And it's strange to remove the extension from the filename when storing, because then you lose information about what kind of file it is (and you aren't storing the MIME type instead either). And you also try to give two different values to obj.ImageName on different lines. This makes no sense.
So all you'd really need is this, I think:
public ActionResult Savedata(HttpPostedFileBase Image)
{
SaveImage obj = new SaveImage();
string result;
if (Image != null)
{
obj.ImageName = Image.FileName;
string imageFolder = "~/DemoImages/";
var path = Path.GetFileNameWithoutExtension(Image.FileName) + DateTime.Now.ToString("ddMMyyhhmmss") + Path.GetExtension(Image.FileName);
result = path.Replace(" ", string.Empty);
var serversavepath = Path.Combine(Server.MapPath(imageFolder) + result);
Image.SaveAs(serversavepath);
obj.ImageName = imageFolder + result;
entity.SaveImages.Add(obj);
entity.SaveChanges();
}
return Content("<script>alert('Data Successfully Submitted');location.href='../Home/Index';</script>");
}
The BindGrid method will be pretty similar, just without the ImagePic field:
public JsonResult BindGrid()
{
DataRow[] result;
var output = (from c in entity.SaveImages.AsEnumerable()
select new
{
ID = c.Id,
ImageName = c.ImageName
}).ToList();
var data = new { result = output };
return Json(output, JsonRequestBehavior.AllowGet);
}
And then in the View, you would only need the following to display it (because the folder name is already in the ImageName field, so it's a ready-made relative URL):
<img src="#item.ImageName" width="100" height="100" />
you could create <img> tag inside td and set base64 string to src attribute.
<tbody>
#foreach (var item in entity.SaveImages)
{
<tr>
<td>#item.Id</td>
<td>#item.ImageName</td>
<td><img src="'data:image/jpg;base64,' + #item.ImagePic" width="100" height="100" /></td>
</tr>
}
</tbody>

Export to excel with hyperlinks, merged cells and text alignment

I am using javascript to generate a large table (of around 15000 rows) and export it to excel. I am converting it into a blob and then exporting using the following code.
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]; }) }
return function(table, name) {
if (!table.nodeType) tableNode = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: tableNode.innerHTML}
str = base64(format(template, ctx));
var blob = b64toBlob(str, "application/vnd.ms-excel");
var blobUrl = URL.createObjectURL(blob);
window.location = blobUrl;
}
It is working fine. However, I am not able to vertically align the text in the excel sheet to the top. I have tried multiple plugins and could not find anything suitable. The table contains
merged cells
hyperlinks
large amount of data
text alignment
I require a solution which will generate the excel file quickly and will support all features
Tried approaches:
- SheetJS was slow since I iterated over the cells and added hyperlinks to a cell in each row.
- Xlsx does not support hyperlinks.
Please let me know a suitable solution. Thanks in advance!
I was able to achieve this by simply adding css to the td vertical-align: top to the table.
Thanks :)

Modify the script to export only visible rows

Currently I am using below script for export data to excel. It's exporting all the available data in Table. I want to modify in such a way that it can only export visible rows. Also I want to add some more columns/informations to the table to be downloaded.
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,filename) {
if (!table.nodeType) table = document.getElementById("testTable");
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
document.getElementById("dlink").href = uri + base64(format(template, ctx));
document.getElementById("dlink").download = filename;
document.getElementById("dlink").click();
}
});
am using $('[style*="display: none"]').remove(); for removing hidden columns. but it also removes data from table. I want to get this remove from only exported data. and want to add some more information in exported sheet.
Any input/suggestion from any of you will be appreciated.

Exporting HTML table to Excel using Javascript

I am exporting HTML table to xls foramt. After exporting if you open it in Libre Office, it works fine but the same opens a blank screen in Microsoft Office.
I don't want a jquery solution please provide any javascript solution.
Please help.
function fnExcelReport() {
var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange;
var j = 0;
tab = document.getElementById('table'); // 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);
}
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();"> EXPORT
</button>
<table id="table">
<thead>
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
On 2016-07-12, Microsoft pushed a security update for Microsoft Office. One of the effects of this update was to prevent HTML files from non-trusted domains from being opened by Excel, because they cannot be opened in Protected mode.
There is ALSO a registry setting that prevents Excel from opening files with the .XLS file extension whose contents do not match the official XLS file format, though it defaults to 'warn', not 'deny'.
Prior to this change, it was possible to save HTML data to a file with an XLS extension, and Excel would open it correctly - possibly giving a warning first that the file did not match the Excel format, depending on the user's value for the ExtensionHardening registry key (or related config values).
Microsoft has made a knowledge-base entry about the new behavior with some suggested workarounds.
Several web applications that previously relied on exporting HTML files as XLS have run into trouble as a result of the update - SalesForce is one example.
Answers from before July 12th 2016 to this and similar questions are likely to now be invalid.
It's worth noting that files produced ON THE BROWSER from remote data do not fall afoul of this protection; it only impedes files downloaded from a remote source that is not trusted. Therefore one possible approach is to generate the .XLS-labelled HTML file locally on the client.
Another, of course, is to produce a valid XLS file, which Excel will then open in Protected mode.
UPDATE: Microsoft has released a patch to correct this behavior: https://support.microsoft.com/en-us/kb/3181507
SheetJS seems perfect for this.
To export your table as an excel file use the code in this link(along with SheetJS)
Just plug in your table element's id into export_table_to_excel
See Demo
If CSV format is good for you, here is an example.
Ok...I just read a comment where you explicitly say it isn't good for you. My bad for not learning to read before coding.
As far I know, Excel can handle CSV.
function fnExcelReport() {
var i, j;
var csv = "";
var table = document.getElementById("table");
var table_headings = table.children[0].children[0].children;
var table_body_rows = table.children[1].children;
var heading;
var headingsArray = [];
for(i = 0; i < table_headings.length; i++) {
heading = table_headings[i];
headingsArray.push('"' + heading.innerHTML + '"');
}
csv += headingsArray.join(',') + ";\n";
var row;
var columns;
var column;
var columnsArray;
for(i = 0; i < table_body_rows.length; i++) {
row = table_body_rows[i];
columns = row.children;
columnsArray = [];
for(j = 0; j < columns.length; j++) {
var column = columns[j];
columnsArray.push('"' + column.innerHTML + '"');
}
csv += columnsArray.join(',') + ";\n";
}
download("export.csv",csv);
}
//From: http://stackoverflow.com/a/18197511/2265487
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();">EXPORT
</button>
<table id="table">
<thead>
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
add this to your head:
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
and add this as your javascript:
<script type="text/javascript">
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]; }) }
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))
}
})()
</script>
Jfiddle: http://jsfiddle.net/cmewv/537/
try this
<table id="exportable">
<thead>
<tr>
//headers
</tr>
</thead>
<tbody>
//rows
</tbody>
</table>
Script for this
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
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.xls`, // 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.xls`, // 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
https://codepen.io/rohithb/pen/YdjVbb
This will download the export.xls file
Hope this will help someone :-)
<hrml>
<head>
<script language="javascript">
function exportF() {
//Format your table with form data
document.getElementById("input").innerHTML = document.getElementById("text").value;
document.getElementById("input1").innerHTML = document.getElementById("text1").value;
var table = document.getElementById("table");
var html = table.outerHTML;
var url = 'data:application/vnd.C:\\Users\WB-02\desktop\Book1.xlsx,' + escape(html); // Set your html table into url
var link = document.getElementById("downloadLink");
link.setAttribute("href", url);
link.setAttribute("download", "export.xls"); // Choose the file name
link.click(); // Download your excel file
return false;
}
</script>
</head>
<body>
<form onsubmit="return exportF()">
<input id="text" type="text" />
<input id="text1" type="text" />
<input type="submit" />
</form>
<table id="table" style="display: none">
<tr>
<td id="input">
<td id="input1">
</td>
</tr>
</table>
<a style="display: none" id="downloadLink"></a>
</body>
</html>
İf you have a too much column , try to use this code. You can split easily.
function iterate( tab, startIndex , rowCount){
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
J=startIndex;
for(j = startIndex ; j < rowCount ; 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));
}
function fnExcelReport()
{
var indirilecekSayi = 250;
var toplamSatirSayisi = 0;
var baslangicSAyisi = 0;
var sonsatirsayisi = 0;
tab = document.getElementById('myTable'); // id of table
var maxRowCount = tab.rows.length;
toplamSatirSayisi = maxRowCount;
sonsatirsayisi=indirilecekSayi;
var kalan = toplamSatirSayisi % indirilecekSayi;
var KalansızToplamSatir=ToplamSatirSayisi-kalan;
var kacKati=Tsh / indirilecekSayi;
alert(maxRowCount);
alert(kacKati);
for (let index = 0; index <= kacKati; index++) {
if (index==kacKati) {
baslangicSAyisi =sonsatirsayisi;
sonsatirsayisi=sonsatirsayisi+kalan;
iterate(tab, baslangicSAyisi, sonsatirsayisi);
}else{
iterate(tab , baslangicSAyisi , sonsatirsayisi);
baslangicSAyisi=sonsatirsayisi;
sonsatirsayisi=sonsatirsayisi+indirilecekSayi;
if(sonsatirsayisi>ToplamSatirSayisi){
sonsatirsayisi=baslangicSAyisi;
}
}
}
}

Superscript in excel sheet while exporting using javascript

I'm exporting a table from a HTML page using the following Javascript code:
<script>
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))
}
})()
</script>
<body>
<table id="maintable">
some table content
</table>
<input type="button" onClick=tableToExcel(maintable,"tablename") />
</body>
This code converts the table to an excel sheet.
But superscript characters are not moved up but stay as it is.
Example: X2 becomes X2 in excel.
I have tried unicode \u00B2 as well but it doesn't work.
Is it possible to export superscript characters to excel?
If yes, how can i achieve this.
Thanks in advance.
[Edit] I get output like X² if I use unicode ² or ² or ²
It turns out that the above script is unable to convert unicode properly.
The best solution that worked for me is using the html tag sup as follows:
<tr>
<td>X<sup>2</sup></td>
</tr>
Hope this helps.

Categories