How to export HTML table into excel using AngularJs - javascript

I'm trying to export data into excel format. it exports into .xls format but when I'm open this file into google sheet it shows an HTML table.
The angularjs Code is
function download(argument)
{
console.log(argument)
var data_type = 'application/xls';
vm.dateForMonth= argument;
//console.log( vm.dateForMonth);
var table_div = document.getElementById('table_wrapper1');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
var blob = new Blob(['\ufeff',table_div.outerHTML], {
// type: "application/xls;charset=utf-8"
// type: "application/vnd.ms-excel;charset=utf-8"
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
console.log(blob);
if(argument!=null || argument != undefined)
{
saveAs(blob, "Time-Sheet_" + vm.dateForMonth+ ".xlsx");
}
else
{
/* var month= moment(new Date()).format("MMM");
console.log(month);
*/
saveAs(blob, "Time-Sheet_" + moment(new Date()).format("MMM YYYY") + ".xlsx");
}
}
}

Related

Exclude table columns while exporting it into Excel in JavaScript

I have to export my HTML table into Excel sheets. I researched a lot and found a solution. It works for me but the problem is, there is some image field in my table data and I want to remove it from table export (suppose the first column). How can I modify my code to get the desired result?
downloadVenues = () => {
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById("venue-table");
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
var filename = 'venues_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();
}
}
Here is a way to remove all the td, tr, th or anything else with a class or id before exporting to Excel.
Set the class .remove-this to any th and td you want to remove.
function exportTableToExcel(tableID, filename = ''){
var table = document.getElementById(tableID);
var cloneTable = table.cloneNode(true);
jQuery(cloneTable).find('.remove-this').remove();
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = cloneTable;
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.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();
}
}
Original code: https://www.codexworld.com/export-html-table-data-to-excel-using-javascript/

How to force dataTableToCsv method in Google Visualization API to escape the hashtag sign

It looks like the dataTableToCsv method stops when it encounters a "#"
Because this is a google defined method, what would be the best way to escape this sign or even better, correct this?
csvContent = csvColumns + google.visualization.dataTableToCsv(data);
Here's a test. Notice that in this example, it will stop at Column D second row.
google.charts.load('current', {
callback: drawBasic,
packages: ['table']
});
function drawBasic() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1w1vaFAPTE440jc2cpYGftXSaPwGxU_x7iQRSGK35oYc/edit#gid=0'
);
query.setQuery('SELECT *');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
title: 'test'
}
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data, options)
$('#Export').on('click', function () {
var csvColumns;
var csvContent;
var downloadLink;
var fileName;
// build column headings
csvColumns = '';
for (var i = 0; i < data.getNumberOfColumns(); i++) {
csvColumns += data.getColumnLabel(i);
if (i < (data.getNumberOfColumns() - 1)) {
csvColumns += ',';
}
}
csvColumns += '\n';
// build data rows
csvContent = csvColumns + google.visualization.dataTableToCsv(data);
// download file
fileName = 'data.csv';
downloadLink = document.createElement('a');
downloadLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
downloadLink.download = fileName;
raiseEvent(downloadLink, 'click');
downloadLink = null;
function raiseEvent(element, eventType) {
var eventRaised;
if (document.createEvent) {
eventRaised = document.createEvent('MouseEvents');
eventRaised.initEvent(eventType, true, false);
element.dispatchEvent(eventRaised);
} else if (document.createEventObject) {
eventRaised = document.createEventObject();
element.fireEvent('on' + eventType, eventRaised);
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button id="Export" title="Download to CSV">Download to CSV</Button>
<div id="chart_div"></div>
You want to download the values of Spreadsheet as a CSV file.
In your current issue, the CSV data is not completed. It's "it will stop at Column D second row".
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
It was found that when I saw csvContent of csvContent = csvColumns + google.visualization.dataTableToCsv(data);, the CSV data has the whole values from the Spreadsheet. So in this modification, csvContent is converted to a blob and it is downloaded.
Modified script:
When your script is modified, please modify as follows.
From:
downloadLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
To:
downloadLink.href = URL.createObjectURL(new Blob([csvContent], {type: "text/csv"}));
or
downloadLink.href = window.URL.createObjectURL(new Blob([csvContent], {type: "text/csv"}));
References:
Blob
URL.createObjectURL()
If I misunderstood your question and this was not the direction you want, I apologize.

Memory issue exporting many JSON records to CSV

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);
}

export data in CSV formate

I Wrote a javascript function to export data into csv formate . Currently getting data in csv file but not in proper ways. I mean they are not in there respective columns. I have a table on page and want data inside that table to be exported to csv file.
function createCSV() {
alert('entered');
var csv = '';
$('table[id$="table"]').find('tr:has(th)').each(function() {
var listThValues = [];
$(this).find('th').each(function() {
listThValues.push($(this).find('div').html());
});
csv += listThValues.join() + '\r\n';
});
$('table[id$="table"]').find('tr:has(td)').each(function() {
var listThValues = [];
$(this).find('td').each(function() {
listThValues.push($(this).html());
});
csv += listThValues.join() + '\r\n';
});
//var filename = 'file.csv';
//var blobby = new Blob([csv], {type: 'text/plain'});
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$("#export").attr({
'download': 'test.csv'
,'href': csvData
,'target' : '_blank' //if you want it to open in a new window
});

JSON to excel file in javascript

I am using the following code to create excel file data from JSON object and then download it on the click of a button.
getExcelFile: function() {
testJson = validation_data;
testTypes = {
"name": "String",
"city": "String",
"country": "String",
"birthdate": "String",
"amount": "Number"
};
emitXmlHeader = function() {
return '<?xml version="1.0"?>\n' +
'<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n' +
'<ss:Worksheet ss:Name="Sheet1">\n' +
'<ss:Table>\n\n';
};
emitXmlFooter = function() {
return '\n</ss:Table>\n' +
'</ss:Worksheet>\n' +
'</ss:Workbook>\n';
};
jsonToSsXml = function(jsonObject) {
var row;
var col;
var xml;
var data = typeof jsonObject != "object"
? JSON.parse(jsonObject)
: jsonObject;
xml = emitXmlHeader();
for (row = 0; row < data.length; row++) {
xml += '<ss:Row>\n';
for (col in data[row]) {
xml += ' <ss:Cell>\n';
xml += ' <ss:Data ss:Type="' + testTypes[col] + '">';
xml += data[row][col] + '</ss:Data>\n';
xml += ' </ss:Cell>\n';
}
xml += '</ss:Row>\n';
}
xml += emitXmlFooter();
return xml;
};
download = function(content, filename, contentType) {
if (!contentType)
contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var a = document.getElementById('test');
var blob = new Blob([content], {
'type': contentType
});
a.href = window.URL.createObjectURL(blob);
a.download = filename;
};
download(jsonToSsXml(testJson), 'validation_data.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
}
But the file created doesn't open in Microsoft Office 2007 and gives the error 'File may be corrupt'. Please help.
I recently got a solution for this question using AlaSQL.
Their working example.
var sheet_1_data = [{Col_One:1, Col_Two:11}, {Col_One:2, Col_Two:22}];
var sheet_2_data = [{Col_One:10, Col_Two:110}, {Col_One:20, Col_Two:220}];
var opts = [{sheetid:'Sheet One',header:true},{sheetid:'Sheet Two',header:false}];
var res = alasql('SELECT * INTO XLSX("sample_file.xlsx",?) FROM ?', [opts,[sheet_1_data ,sheet_2_data]]);
Libraries required:
<script src="http://alasql.org/console/alasql.min.js"></script>
<script src="http://alasql.org/console/xlsx.core.min.js"></script>
NOTE: Don't pass undefined values to the function. Generated file will produce warning messages if you try to open them in this case.
Other options were able to convert JSON to CSV (not XLSX).

Categories

Resources