Hey Guys i wanted to create a link which creates a csv of my JSON array.
My Code creates a CSV File every time when i reload my page
i can't see a link, where i can click. I'm really beginner of JS
Could Someone help me?
var csvContent = "data:text/csv;charset=utf-8,";
// Iterating through all the objects
data.forEach(function (infoArray, index) {
// Fetching all keys of a single object
var _keys = Object.keys(infoArray);
var dataString = [];
[].forEach.call(_keys, function(inst, i){
dataString.push(infoArray[inst]);
});
dataString = dataString.join(";");
csvContent += index < data.length ? dataString + "\n" : dataString;
});
var encodedUri = encodeURI(csvContent);window.open(encodedUri);
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
link.click();
you have created a link , but you need append it somewhere
for example
document.body.appendChild(link)
I used it like this
It works
<input id="csv" type="button" value="CSV">
//--------------------------- CSV EXPORT --------------------------------
var csvContent = "data:text/csv;charset=utf-8,";
$("#csv").click(function(){
// Iterating through all the objects
data.forEach(function (infoArray, index) {
// Fetching all keys of a single object
var _keys = Object.keys(infoArray);
var dataString = [];
[].forEach.call(_keys, function(inst, i){
dataString.push(infoArray[inst]);
});
dataString = dataString.join(";");
csvContent += index < data.length ? dataString + "\n" : dataString;
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
link.click();
});
Related
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/
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.
Hi I am generating a CSV file based on some filtered data in my angular web app.
The input I am sending to my csvString is:
Torup Bakkegård (Middelfartvej 105); Coop Brøndby; (Holkebjergvej 54);
The output is always ruined once i open the excel file:
TorupBakkegård(Middelfartvej105) CoopBrøndby(Holkebjergvej54)
However when I open it with notepad it's fine, so it's just MS Excel(using the latest version) that seems to ruin it.
TorupBakkegård(Middelfartvej105);CoopBrøndby(Holkebjergvej54);
I tried with several encodings, it seems excel simply does not care
Here is the code javascript:
vm.downloadExcel = function (bookings) {
var csvRows = [];
var csvHeading = "Afhentningsadresse;Modtager";
csvRows.push(csvHeading + "\n");
for (var i = 0; i < bookings.length; i++) {
var csvRow = "";
csvRow += bookings[i].pickupAddress + ";";
csvRow += bookings[i].customerAddress + ";";
csvRows.push(csvRow + "\n");
}
var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:application/csv;charset=Windows-1252,' + csvString;
a.target = '_blank';
a.download = 'myFile.csv';
console.log(a.href);
document.body.appendChild(a);
a.click();
After a bit of research we figured out that we didn't mention the BOM.
The BOM is responsible for the encoding in the actual file.
So after changing:
a.href = 'data:application/csv;charset=Windows-1252,' + csvString;
With:
a.href = 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURI(csvString);
Everything works just fine.
Credits goes to: Gergő Nagy, for answering:
Javascript to csv export encoding issue
I am using handsontable plugin for generate the data as excel format. This is done.
I need to export that data as excel and download.
Is there feature available in handsontable?
If not, How can i achieve this? Here, Handsontable data is different in table format
There isn't a feature yet, it's coming in the Pro version next month. In the meantime, there's this stack answer with a solution you could implement. You want to parse the data object from handsontable and then export that string to csv the normal JS way.
And here is the fiddle in case you don't want to follow the link, with the relevant code:
function parseRow(infoArray, index, csvContent) {
var sizeData = _.size(hot1.getData());
if (index < sizeData - 1) {
dataString = "";
_.each(infoArray, function(col, i) {
dataString += _.contains(col, ",") ? "\"" + col + "\"" : col;
dataString += i < _.size(infoArray) - 1 ? "," : "";
})
csvContent += index < sizeData - 2 ? dataString + "\n" : dataString;
}
return csvContent;
}
/**
* Export to CSV button
*/
var exportCsv = $("#export-csv")[0];
if (exportCsv) {
Handsontable.Dom.addEvent(exportCsv, "mouseup", function(e) {
exportCsv.blur(); // jquery ui hackfix
var csvContent = "data:text/csv;charset=utf-8,";
csvContent = parseRow(colHeaders, 0, csvContent); // comment this out to remove column headers
_.each(hot1.getData(), function(infoArray, index) {
csvContent = parseRow(infoArray, index, csvContent);
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", $("h1").text() + ".csv");
link.click();
})
}
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);
}