I need to export data in '.XLSX' file for Chrome browser below code is working fine for IE.
But code in else condition is creating download.xls file Chrome browser
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
Below is the code used on Button Click :
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,"ABCD.xlsx");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
Please help me on this, thanks in advance.
Please suggest me solution with above code , I am new to javascript and unable to implement the solution in suggested link .
I have also used below code to create .XLSX file, Code is creating file but file is blank and showing an error message:
"The file Format and extension do not match.The file could be corrupted or unsafe......Do u want to opent it anyway"
var a = document.createElement('a');
var data_type = 'data:application/vnd.ms-excel';
var table_div = tab_text; //Your tab_text
var table_html = table_div.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table.xlsx';
//triggering the function
a.click();
You can do like this:
window.saveAs(blob,filename);
function fnExcelReport(id, name) {
var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets>
<x:ExcelWorksheet>';
tab_text = tab_text + '<x:Name>Test Sheet</x:Name>';
tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions>
</x:ExcelWorksheet>';
tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
tab_text = tab_text + "<table border='1px'>";
var exportTable = $('#' + id).clone();
exportTable.find('input').each(function (index, elem) { $(elem).remove(); });
tab_text = tab_text + exportTable.html();
tab_text = tab_text + '</table></body></html>';
var fileName = name + '_' + parseInt(Math.random() * 10000000000) + '.xls';
//Save the file
var blob = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" })
window.saveAs(blob, fileName);
}`
Related
I have a web page with a table which generates once from a XMLHttpRequest. The response includes a JSON with some text and associated links to three attachments that may or may not be there, so I have to loop through those to store variables and create links, like so:
function drawWITable(tableObjArr) {
tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries.reverse();
var tableCount = Object.keys(tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries).length;
var tableHeader = "<table><tr><th class='general'>ФИО</th><th class='general'>Примечания</th><th class='general'>Дата создания</th><th class='general'>Группа</th><th class='attch1'> </th><th class='attch2'> </th><th class='attch3'> </th></tr>";
var tableContent = "";
for(i = 0; i < tableCount; i++) {
tableContent = tableContent + "<tr class='hoverHL'><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values.FullName + "</td><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Detailed Description"] + "</td><td>" + moment(Date.parse(tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log Submit Date"])).format('dd, MMMM DD YYYY, HH:mm:ss') + "</td><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values.DftSupportGroup + "</td>";
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log01"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName1 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log01"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment1(authToken, wrklgID, attachName1);'>" + "1" + "</td>";
}
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log02"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName2 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log02"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment2(authToken, wrklgID, attachName2);'>" + "1" + "</td>";
}
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log03"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName3 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log03"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment3(authToken, wrklgID, attachName3);'>" + "1" + "</td>";
}
tableContent = tableContent + "</tr>";
}
var tableFooter = "</table>";
document.getElementById("request-worklog").innerHTML = tableHeader + tableContent + tableFooter;
$("#request-worklog table tbody tr th").resizable({
minHeight: 20,
maxHeight: 20
});
}
Then, by clicking either of the attachment areas user should be able to download file.
function getAttachment1(authToken, wrklgID, attachName1) {
var data = "undefined=";
var request = new XMLHttpRequest();
request.withCredentials = true;
request.open("GET", "http://XXXXXXXXXXXXXXXX/v1/entry/WOI:WorkInfo/" + wrklgID + "/attach/z2AF%20Work%20Log01", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Authorization", authToken);
request.setRequestHeader("Cache-Control", "max-age=0");
request.responseType = "blob";
request.send(data);
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = request.response;
console.log(content);
}
};
}
Right now after clicking I only get network response in form of
PNG
IHDRrWؼøsRGB®ÎégAMA±üa pHYsÒÝ~ütIMEÞ,-ËòtEXtSoftwarepaint.net 4.0.9l3~NIDATx^íTÕÙÇMóK5Ý.Ò¤
R-Ö|ES±1*ÁìF£_H+±¤ÇXbÔ¨`OÑÙÙ]vvg]¶²Íóýÿï9çÎ;gª|qÞçù=sË9ï9÷üï©÷ÞÙI)ÕVfçn
©÷½2;ïmÝu
*zÀxU±ßF¦|fÈ(ÍÐÑa¢ÃÒì?F3b¬fä8Í£Æ&hFOb¬9ÈaÌ!±jÆf¤¸fBøÄÉ1-dWMdÄ{Ñe¶kÜÑ1æ
9Ö°Ìö±íTÈû«HóýcÌ#d¨]ÂN<as÷ á ûTðÑoôæ+çÄý0cÌ£/9ÉB>FU`TV[^aì¨o°&2èÂÄ4a"£ÄêÙsUÃ57ªæ_=¬Züj}êiµyÍêþêTÕ×NTlãäDö¢"}§0¼èqÒ|ô~qß=_%äÇbÌ#$âù«j{þÅ?>&àbOÑq{> qå*ã!j¿Á#e(ßpÃ-ª3Wïõô¸ó£ëª¬DØâ¦Ñ7W>1#ý©Mw.üµ>ýÅPß6Õ_?IÊ¡õñ§À*qÆ|=mÁ9¶u¯R-xLµ<ö¸æO?kW`áOñæg¤W(Æ!Yyµª·½]ÎZë®Ià\ö2CõvtÐÚÚÖ½¬çcYâ¨]uªM ]vñ|Ö¬W3ÏÍ+&k
o,Þ L´<ön=rÄsì1#uUWk½½ò\¼TûàyÔ¨¦Õ÷©Þ-[tÒÝ®®ª#5]?ý\Û6BJá6ßû .¤5ÐD*ÁV®ÎèGÓÒr´F1+'NõÏ"5.[.ïZrÉ5éBÞ{FBêÈã¶Òò$¢Ì޴ƧÌTïántmíKÞ»^Dì;Lµüù´Â}?ÖüУ(4sü{AjkÝUEÿüM3Ç
½m\ÎL7©AÓ
!ï{ äë©N·#}ÀBRDô'õHÖæMÓôHSÄ&-Gó»éÖÛuÁòMHúJ.½Á'HúÔp\Z!B¦]C6pmlZCi1WÈõI
BFær*ìì4¡µi!Cíļóå2ÌØS¿I5þr¥ªùÆéªrÖñàkØþ®jZuêÝÜì-Tk³¾/MHZOs3FÊèR¦Ç×êãNÚw"dâÔ³T|Ʊ*¡äW8N3óx
®Oº púbìRâ¢_ì®KfÔBÄoZ}¿´iÓ¢ #Ç©æGÁß±Ð+8÷tâæén¾Dý-ÿyÇ+"!«Ød2û¿\¸é1GH®ðó$"BþÄ;^!fMjÃÍ?òzQC]ù^úÜÌ»koÊ*fÝ%KtáØt)$¦PÙjr/
OÂéÔ-\ìo9%/¿:]Èû1p YyÄ1~·6Æ etc...
As well as this in the console:
Blob {size: 6698, type: "application/octet-stream"}
size: 6698
type: "application/octet-stream"
__proto__: Blob
What should I do next? How to initiate the download process? I am able to get a name of an attachment from the other side, but that's it, no type or anything. Official documentation isn't much of a help either. I am fairly new to JS, so maybe it's something simple that I'm missing?
Thank you!
If you want the browser download a image instead of show it,you need to set a http header Content-Disposition: attachment.
And you should not use xhr,you should jump to link.
To download after getting the content:
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = request.response;
_html5Saver(content, 'myfile.png');
}
};
}
function _html5Saver(blob , fileName) {
// to emulate click action
// because we cannot save directly to client's computer due to security constraints
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
document.body.removeChild(a);
}
Use this to view your file
let blob = new Blob([byteArray], {type: contentType});
var blobURL=URL.createObjectURL(blob);
window.open(blobURL);
I have a function that converts a HTML table into an Excel document. However upon the opening of the file, I receive the following message from Excel:
The file format and extension of 'something.xls' don't match. Etc etc...
Below is the function I am for the export, it is a slightly edited version of #SamPopes answer from this thread. The obj parameter is a table element I created using document.createElement('table');.
Is there any way to prevent this message upon opening the file?
function export(obj) {
var tab_text="<table border='2px'><tr>";
var textRange; var j=0;
tab = obj; //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 you want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if you want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // removes 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,"export.xls");
} else { //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
}
As I said in my comment above, here is the code for creating a CSV file. This works to avoid the error message you are receiving, but will eliminate any chance you have for formatting your data (As far as I know). Here is my code, which uses one process for IE and a second for all other browsers:
function exportTotalDataFile(){
var dataText = "";
var rowText = "";
'allData is generated through an AJAX call that creates a JSON'
'this loop creates the header row'
for (var index in allData[0]) {
rowText += index + ',';
}
'takes the trailing comma out, adds new row'
rowText = rowText.slice(0, -1);
dataText += rowText + '\r\n';
'Produces the data rows'
for (var i = 0; i < allData.length; i++) {
var rowText = "";
for (var index in allData[i]) {
rowText += '"' + allData[i][index] + '",';
}
rowText.slice(0, rowText.length - 1);
dataText += rowText + '\r\n';
}
var fileName = "Losses Report";
'Internet Explorer logic'
var isIE = false || !!document.documentMode;
if (isIE){
var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + dataText);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();
}
'All the other browsers'
else {
var uri = 'data:text/csv;charset=utf-8,' + escape(dataText);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
Sorry that this method is limited in the formatting department, but I hope this helps
I am using the code below to export nearly 3,000 JSON records to CSV format. It is working in Chrome and Opera but not in Safari, IE, or Firefox. I have an "out of browser memory" issue.
Why doesn't it work in those browsers?
How can I export many (e.g. 90,000) records in any browser?
function exportAll(JSONData, ReportTitle, ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
CSV += ReportTitle + '\r\n\n';
if (ShowLabel) {
var row = "";
for (var index in arrData[0]) {
row += index + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
var link = document.createElement("a");
link.id = "lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
blob = new Blob([csv], {
type: 'text/csv'
});
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = 'GraphsData.csv';
$("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
$('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
please help me my probs,am using kendo ui grid in my webapp & trying to grid data export into EXcel and CSV format. Code Works good in Chrome and files are downloading, but in Fire Fox its open a new window show the grid details in url and says bad request,
//code is
$("#exportcsv").click(function (e) {
debugger
var dataSource = $("#grid").data("kendoGrid").dataSource;
var filteredDataSource = new kendo.data.DataSource({
data: dataSource.data(),
filter: dataSource.filter()
});
filteredDataSource.read();
var data = filteredDataSource.view();
//start with the desired column headers here
var result = "\"ID\",\"EID\",\"Name\",\"Company Name\",\"Salary\",\"DID\",\"Date Of Join\"";
//each column will need to be called using the field name in the data source
for (var i = 0; i < data.length; i++) {
result += "\n";
result += "\"" + data[i].id + "\",";
result += "\"" + data[i].EID + "\",";
result += "\"" + data[i].EName + "\",";
result += "\"" + data[i].CName + "\",";
result += "\"" + data[i].Salary + "\",";
result += "\"" + data[i].DID + "\",";
result += "\"" + data[i].DOJ + "\",";
}
if (window.navigator.msSaveBlob) {
//Internet Explorer
window.navigator.msSaveBlob(new Blob([result]), 'ExportedKendoGrid.csv');
}
else if (window.webkitURL != null) {
//Google Chrome and Mozilla Firefox
var a = document.createElement('a');
result = encodeURIComponent(result);
a.href = 'data:application/csv;charset=UTF-8,' + result;
a.download = 'ExportedKendoGrid.csv';
a.click();
}
else {
//Everything Else
window.open(result);
}
e.preventDefault();
});
//below code is not working in firefox browser else if
(window.webkitURL != null) {
//Google Chrome and Mozilla Firefox
var a = document.createElement('a');
result = encodeURIComponent(result);
a.href = 'data:application/csv;charset=UTF-8,' + result;
a.download = 'ExportedKendoGrid.csv';
a.click();
}
Want to Export dynamic html table to excel in javascript is there any way can i do do in firefox browser without using activex object in code .please help me
Here's a function for doing this in Firefox with JavaScript, assuming the user has Excel installed on their machine:
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))
}
})()
jsFiddle live example:
http://jsfiddle.net/insin/cmewv/
You can dynamically generate the Excel file in SpreadsheetDataXML format which allows you to custom the table, cell styles and format in HTML syntax.
To make this work in IE you'll need to use Blob object and then call msSaveBlob method.
For FF and Chrome, you can just change the data of href to data:application/vnd.ms-excel
function fnExcelReport() {
var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
tab_text = tab_text + '<x:Name>Test Sheet</x:Name>';
tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
tab_text = tab_text + "<table border='1px'>";
tab_text = tab_text + $('#myTable').html();
tab_text = tab_text + '</table></body></html>';
var data_type = 'data:application/vnd.ms-excel';
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
if (window.navigator.msSaveBlob) {
var blob = new Blob([tab_text], {
type: "application/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, 'Test file.xls');
}
} else {
$('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
$('#test').attr('download', 'Test file.xls');
}
}
Working example: http://jsfiddle.net/h42y4ke2/21/
YT tutorial: https://www.youtube.com/watch?v=gx_yGY6NHkc
AFAIK there's no library for creating a real excel file in JavaScript but you might try and export the table in HTML to a file with .xls extension.
There is an extension table2clipboard for firefox. You can also generate csv output from DOM tree manually and let user save it as csv file. Excel can import from CSV.