Can we save file from html page in android device using javaScript - 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

Related

How to properly export to CSV in 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();

Angular save file as csv result in Failed- network error Only on Chrome

I'm using the following code to save file as csv.
$scope.saveCSVFile = function (result)
{
var a = document.createElement('a');
a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(result.data);
a.target = '_blank';
a.download = $scope.getFileNameFromHttpResponse(result);
document.body.appendChild(a);
a.click();
$scope.isReportInProgress = false;
};
The file is working on most of the cases but for some reason when the file is larger than 10MB i get "Failed - Network Error".
It happens only on chrome.
I tried to search the web for this issue and couldn't find anything relevant.
Can you think of an idea why does it happens? or maybe use a different save file method that will work on chrome/firefox/IE instead of my function?
I was finally used this one, hope it can help the next one encounter this issue:
var blob = new Blob([result.data], {type: 'text/csv'});
var filename = $scope.getFileNameFromHttpResponse(result);
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
I had a similar problem, but had to serve a zip file, sent from the server in base64 format. What did the trick for me:
function downloadBlob(data, filename) {
const blob = new Blob([new Buffer(data, 'base64')], {type: 'application/octet-stream'});
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
const elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
window.URL.revokeObjectURL(elem.href);
document.body.removeChild(elem);
}
}
return (
{/* ... */}
<a href="#" onClick={() => {downloadBlob(report.zip, `${report.filename}.zip`)}}>
Download <b>{report.filename}.zip</b>
</a>
{/* ... */}
);
I left the function because like the fact that it revokes the URL after serving the file.

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).

Export in CSV from JSON in IE through javascript

How to download table rows in CSV format in Internet Explorer from client side? At present I am using the below URI method to download it in other browser. But it seems Internet Explorer does not support the below mechanism. I want to support from IE version 8 till the latest. Any help for IE would be appreciated.
var fileName = "Result";
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
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);
I got the solution for it which is supporting IE 8+ for me. We need to specify the separator as shown below.
if (navigator.appName == "Microsoft Internet Explorer") {
var oWin = window.open();
oWin.document.write('sep=,\r\n' + CSV);
oWin.document.close();
oWin.document.execCommand('SaveAs', true, fileName + ".csv");
oWin.close();
}
You can go through the link http://andrew-b.com/view/article/44

Categories

Resources