How to properly export to CSV in JavaScript? - javascript

I have a JavaScript function that enables me to download a CVS file. When I open this file in excel, everything is placed in the same column instead.
This is my code:
function convertToCSV(dataArray) {
var csvContent = "data:text/csv;charset=utf-8,";
dataArray.forEach(function(infoArray, index)
{
dataString = infoArray.join(",");
csvContent += index < dataArray.length ? dataString+ "\n" : dataString;
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "download.csv");
document.body.appendChild(link);
link.click();
}
This is what it looks like:
This is the output I'm expecting:
What am I doing wrong? Any help would be appreciated.
NB: I have been looking for a way to export straight to an .xlsx or .xls file, but I didn't win.

You can use mongo-xlsx module to export your data to xlsx file
var mongoXlsx = require('mongo-xlsx');
var data=dataArray;
var model=mongoXlsx.buildDynamicModel(data);
mongoXlsx.mongoData2Xlsx(data, model, function(err, data) {
console.log("data",data);
console.log('File saved as:', data.fullPath);
});
Hope this helps

You could do this with native js fairly easily like so:
let text = '';
dataArray.map(arr => text += arr.join(',') + '\r\n');
let link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + escape(text));
link.setAttribute('download', 'download.csv');
document.body.appendChild(link);
link.click();

Related

Download HTML table to Excel by using Javascript

In my Flask application, I created a button to extract the content of an HTML table into an Excel file. I used Javascript to extract from my interface the content of my HTML table in Excel format.
Unfortunately, when I run the code below, the downloaded Excel file is empty. Could you please help to correct my code below. Thanks.
function exportTableToExcel(filename = ''){
let downloadLink;
let dataType = 'application/vnd.ms-excel';
let tableSelect = document.getElementsByTagName("table");
let tableHTML = tableSelect[0].outerHTML.replace(/ /g, '%20');
// Specify file name
filename = 'All_Issues.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();
}
}
The getElementsByTagName() function returns an array so you have to get the first element.
let tableHTML = tableSelect[0].outerHTML.replace(/ /g, '%20');

Export contents inside <div> as a .docx File

I am having trouble exporting the contents of a div into a .docx file. I am using FileSaver.js which can be found here: https://github.com/eligrey/FileSaver.js/.
My JavaScript Function:
function exportNote(){
var blob = new Blob([document.getElementById('editor').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8"
});
saveAs(blob, "note.docx");
}
I get a download that appears to be a word file but when I open it I get the following error:
The Open XML file note.docx cannot be opened because
there are problems with the contents or the file name
might contain invalid characters (for example. /).
Details:
The file is corrupt and cannot be opened.
For graphical purposes:
The text area is the area I am trying to export into a word document which is under <div id="editor"></div>.
jsfiddle
Html
<div id="main">
this is content of div
</div>
JavaScript
function downloadInnerHtml(filename, elId) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + 'text/doc' + ';charset=utf-8,' + encodeURIComponent(elHtml));
link.click();
}
var fileName = 'tags.doc'; // You can use the .txt extension if you want
downloadInnerHtml(fileName, 'main');
There is another solution to this problem using an open source library on github under the MIT license: https://github.com/evidenceprime/html-docx-js.
My solution:
function exportNote(contentId){
var filename = 'note.html'
var htmlDoc = document.getElementById(contentId).innerHTML;
var converted = htmlDocx.asBlob(htmlDoc);
saveAs(converted, "notes.docx");
}
Since somebody had a problem in the comments, I'm pasting in what I am actively using. The function I pasted here is darn near verbatim from this site: https://www.codexworld.com/export-html-to-word-doc-docx-using-javascript/
So credit to them. The key to this is that saving the contents of a div to a file is not a proper HTML document, and that causes Word to balk. It needs a BODY, HTML and some of that xmlns attributing. This function gets the innerHtml and wraps it with that, before doing the actual save.
Simply call Export2Word() with the name of the element that holds the content you want to save and the filename:
Export2Word('divMyContent','MyFileNameWithoutExtension');
function Export2Word(element, filename = ''){
var preHtml = "<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 postHtml = "</body></html>";
var content = document.getElementById(element).innerHTML;
var html = preHtml+content+postHtml;
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+'.docx':'document.docx';
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob ){
navigator.msSaveOrOpenBlob(blob, filename);
}else{
// Create a link to the file
downloadLink.href = url;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
document.body.removeChild(downloadLink);
}

javascript download csv data in Safari

Is there anyway to download a csv string that I have created in my javascript in Safari?
EDIT: I do not want to (cannot) create a file on the server.
I have the following code, it will work fine on other browsers, but not on safari. The best that I can seem to make it do is open the data in a new window, but that is an awful UI experience for the user.
$("#csv").click(function(event) {
event.preventDefault();
navigator.sayswho = (function() {
var ua = navigator.userAgent, tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
return M[1];
})();
var download = function (content, fileName, mimeType) {
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
mimeType = 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
return navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if ('download' in a) { //html5 A[download]
a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
a.setAttribute('download', fileName);
document.body.appendChild(a);
setTimeout(function () {
a.click();
document.body.removeChild(a);
}, 66);
return true;
} else { //do iframe dataURL download (old ch+FF):
if (navigator.sayswho == 'Safari') {
var uri = 'data:text/csv;charset=utf-8,' + escape(content);
var link = document.createElement("a");
link.href = uri;
link.target = "_blank";
link.style = "visibility: hidden";
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
else
{
var f = document.createElement('iframe');
document.body.appendChild(f);
f.src = 'data:' + mimeType + ',' + encodeURIComponent(content);
setTimeout(function () {
document.body.removeChild(f);
}, 33333);
return true;
}
}
}
//csv_content is my string that has the csv data in it.
download(csv_content, moment().format("YYYY_MM_DD_HH_mm") + '.csv', 'text/csv');
});
In Chrome and in FireFox, it works as expected. I saw some answers using FileSaver.js (https://stackoverflow.com/a/14858315/1758023), but the comments say this is not working (and I couln't make it work either).
Try using the following js function.
function download()
{
window.location = '<<your file name with full path>>';
//for ex. function download()
//window.location = 'mobilepayreport.xls';
}
I also had the issue in safari.You can create and download the csv file in safari.But until your file is not physically stored on any location it does not show the file name and type in download popup(it always shows unknown).So I suggest pass the data as html in server side code using ajax and create a file and and with response of that call create the link of file which you stored from server side code.download the file and then you can delete this file.

File Write Operation in javascript

I need to write into a file in javascript.I tried below Code.I got error like"FileWriter is not defined".please help me in this.
<html>
<head>
</head>
<body>
<input type = "button" value = "write" onclick="WriteFile()">
<script>
function WriteFile()
{
var fileWriter = new FileWriter("C:\Users\ananthi\Desktop\readme.txt");
fileWriter.open() ;
fileWriter.writeLine("Another line") ;
fileWriter.close() ;
}
</script>
</body>
</html>
If you would like to use button call function:
<input type = "button" value = "write" onclick="Download()">
Download () {
let filename = "readme.txt";
let text = "Text of the file goes here.\n1";
let blob = new Blob([text], {type:'text/plain'});
let link = document.createElement("a");
link.download = filename;
//link.innerHTML = "Download File";
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}, 100);
}
The File Writer API is defunct and never saw significant browser support.
You cannot write files from browser-based JavaScript. What you do instead is provide the user with a link that they can download, like this:
var filename = "readme.txt";
var text = "Text of the file goes here.";
var blob = new Blob([text], {type:'text/plain'});
var link = document.createElement("a");
link.download = filename;
link.innerHTML = "Download File";
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);
That works on browsers that support the File API (which modern ones do, but not IE9 or earlier).

Can we save file from html page in android device using javaScript

I am prompting window on desktop to save file on local device by using following code
if (finalResult == '') {
alert("Invalid data");
return;
}
var result2 = nameObject.personalInfo[0].Name;
var result3 = nameObject.personalInfo[0].Number;
var fileName = result2 + result3;
var uri = 'data:text/csv;charset=utf-8,' + escape(finalResult);
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);
location.reload();
By this user can get CSV into excel. Will same code work for android devices?
If not then please suggest me alternatives.
Thank you

Categories

Resources