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/
Related
i want to save chart html to word file as image
but word file can download but chart image is just X image it means doesn't have data
could you give me solution
function ExportToDoc(filename = "") {
html2canvas(document.getElementById("pyramid")).then((canvas) => {
canvas.toBlob((blob) => {
if (blob) {
myBlob = blob;
}
});
});
var HtmlHead =
"<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var EndHtml = "</body></html>";
//complete html
// var html = HtmlHead + document.getElementById("pyramid").innerHTML + EndHtml;
var html =
HtmlHead +
"<img src='" +
URL.createObjectURL(
new Blob(new Uint8Array(myBlob), { type: "image/png" })
) +
"'/>" +
EndHtml;
// "<div id='export'><img class='hide' src='" + URLObj.createObjectURL() +"'/></div>"
//specify the type
var blob = new Blob(["\ufeff", html], {
type: "application/msword",
});
// Specify link url
var url =
"data:application/vnd.ms-word;charset=utf-8," + encodeURIComponent(html);
// Specify file name
filename = filename ? filename + ".doc" : "document.doc";
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, filename);
} else {
downloadLink.href = url;
downloadLink.download = filename;
downloadLink.click();
}
document.body.removeChild(downloadLink);
}
enter image description here
for HTML
<Chart
id="pyramid"
...
</Chart>
chart is working well
function ExportToDoc(filename = "") {
var img = new Image();
html2canvas(document.getElementById("pyramid")).then((canvas) => {
img.src = canvas.toDataURL();
var HtmlHead =
"<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var EndHtml = "</body></html>";
var html =
HtmlHead + "<img class='hide' src='" + img.src + "'/>" + EndHtml;
var blob = new Blob(["\ufeff", html], {
type: "application/msword",
});
var url =
"data:application/vnd.ms-word;charset=utf-8," +
encodeURIComponent(html);
filename = filename ? filename + ".doc" : "Document.doc";
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, filename);
} else {
downloadLink.href = url;
downloadLink.download = filename;
downloadLink.click();
}
document.body.removeChild(downloadLink);
});
}
I solved it by myself.
Also upgraded:
function htmlToFile(element, file = "hwp") {
var img = new Image();
html2canvas(document.getElementById("pyramid")).then((canvas) => {
img.src = canvas.toDataURL();
var header = "<html><head><meta charset='utf-8'></head><body>";
var footer = "</body></html>";
var sourceHTML =
header + "<img class='hide' src='" + img.src + "'/>" + footer;
var source =
"data:application/vnd.ms-word;charset=utf-8," +
encodeURIComponent(sourceHTML);
var fileDownload = document.createElement("a");
document.body.appendChild(fileDownload);
fileDownload.href = source;
fileDownload.download = "Document." + file;
fileDownload.click();
document.body.removeChild(fileDownload);
});
}
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.
<script type="text/javascript">
$(document).ready(function () {
//getting values of current time for generating the file name
$(".toExcelButton").click(function(){
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('dvData');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table_' + postfix + '.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
})
});
</script>
Need to export div tables to excel. The above code works fine in Chrome but not working in IE. Can anyone help me out on the same.
In IE a dynamically created anchor tag needs to be added to the DOM to execute its click event. Furthermore the download attribute is not supported in the IE:
Download attribute on A tag not working in IE
Edit:
Recently I posted many answers handling this issue, here are two of those:
image does not download with it's own extension
JS Base64 string to downloadable pdf - Edge
Basically you have to use msSaveOrOpenBlob() in IE:
var tF = 'Whatever.xls';
var tB = new Blob(..);
if(window.top.navigator.msSaveOrOpenBlob){
//Store Blob in IE
window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
//Store Blob in others
var tA = document.body.appendChild(document.createElement('a'));
tA.href = URL.createObjectURL(tB);
tA.download = tF;
tA.style.display = 'none';
tA.click();
tA.parentNode.removeChild(tA)
}
In the case above:
var tT = new XMLSerializer().serializeToString(document.querySelector('table')); //Serialised table
var tF = 'Whatever.xls'; //Filename
var tB = new Blob([tT]); //Blob
if(window.top.navigator.msSaveOrOpenBlob){
//Store Blob in IE
window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
//Store Blob in others
var tA = document.body.appendChild(document.createElement('a'));
tA.href = URL.createObjectURL(tB);
tA.download = tF;
tA.style.display = 'none';
tA.click();
tA.parentNode.removeChild(tA)
}
https://jsfiddle.net/23ao1v0s/1/
Please check the below given link. I think you will get a solution for your question
https://github.com/rainabba/jquery-table2excel
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();
});
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
});