export data in CSV formate - javascript

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

Related

How to export HTML table into excel using AngularJs

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

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.

Export to csv using java script

I am facing problem with exporting csv.
Problems:
1) I have to export a html table to csv file . Can i change the delimiter of csv file to something else like semicolon. If I have values in the table under the same column separated by comma, in the csv sheet it is showing in a different column.
2) My code is not working for IE and it is only working for mozilla
3) Also I wanted the user to save the csv file. Now it is getting automatically saved.
Please find my code . Can any body help with any of the issue.
function exportTableToCSV(filename) {
var tab = $('#searchObjectTableTabs').tabs('getSelected');// selecting the table
var tabIndex = $('#searchObjectTableTabs').tabs('getTabIndex', tab);
var data;
var rows;
if (tabIndex == '0') // first index of the tab under which the table will be displayed
{
data = $('#dg');//Only one table
rows = $('#dg').datagrid('getRows');
} else if (tabIndex == '1') // second index
{
data = $('#doc').first(); //Only one table
rows = $('#doc').datagrid('getRows');
}
var csvData = [];
var tmpArr = [];
var tmpStr = '';
data.find("tr").each(function ()
{
if ($(this).find("th").length) {
$(this).find("th").each(function () {
tmpStr = $(this).text().replace(/"/g, '""');
tmpArr.push('"' + tmpStr + '"');
});
csvData.push(tmpArr);
}
tmpArr = [];
$.each(exportArray, function (index, value)
{
csvData.push(exportArray[index].type + "," + exportArray[index].status + "," + exportArray[index].ID + "," + exportArray[index].itemrev + "," + exportArray[index].desc + "," + exportArray[index].owner + "," + exportArray[index].ogrp);
});
csvData.push(tmpArr.join('\n'));
// printObject(tmpArr);
});
alert('before this');
var output = csvData.join('\n');
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(output);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
'delimiter':';'
});
alert('done');
}
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this,['export.csv']);
});

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

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