Unable to export .csv file in IE browser - javascript

I'm trying to export my data as CSV file. I wrote below code, that is working fine in Firefox/Chrome but not in IE. I need to make work in IE8/9/10 versions. Thanks in advance.
JS code:
var CSVgen = function (CSV, ReportName) {
//Generate a file name if empty is replace by _.
var fileName = ReportName.replace(/ /g,"_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;Content-Type:application/octet-stream;Content-Disposition: attachment;charset=utf-8,' + escape(CSV);
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
And i tried below ways also:
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
and
var uri = 'Content-Type:application/octet-stream;Content-Disposition:
attachment;' + escape(CSV);
But no luck. I'm getting below error page in IE:
The webpage cannot be displayed
Most likely cause:
•Some content or files on this webpage require a program that you don't have installed.
What you can try:
Search online for a program you can use to view this web content.
Retype the address.
Go back to the previous page.

Related

downloaded html page not opening in chrome or edge but in IE and giving noscript error - vue application

In my application, i am trying to download html of current page which is with same domain name. I have written some method to download the html and it is downloading.
But, i have tried to open it in chrome as well as edge and it is not opening. But, in IE it is opening and displaying text of noscript tag (We're sorry but app doesn't work properly without JavaScript enabled.Please enable it to continue.).
I am inputting intranet site URL and clicking the download button. Here is my method below.
downloadHtml() {
let url = this.urlInput; // input text v-model value
fetch(url)
.then((res) => res.text())
.then((html) => this.downloadAsFile("report.html", html)); // by this name it is downloading
},
downloadAsFile(name, text) {
const link = this.createDownloadableLink(name, text);
const clickEvent = new MouseEvent("click");
link.dispatchEvent(clickEvent);
},
createDownloadableLink(fileName, content) {
let link = document.createElement("a");
link.href = 'data:attachment/text,' + encodeURIComponent(document.documentElement.outerHTML);
link.target = '_blank';
link.download = fileName;
return link;
},
**The problems are :
1. The app root signifies the public/index.html and that downloaded html is this one not the current page's html.
2. Chrome or Edge is not opening that html page even i checked browser is javascript enabled.
So, what i have to change the download the current page html?
The problem is that an HTML file in not an application/octet-stream file type. The mime type of an HTML page is text/html
I'm unsure of the way you try to create your download link. I don't have time to test it, but there is the way I do it usually using the createObjectURL API :
async function fetchHTML(url) {
let content = await fetch(url).then(resp => resp.text());
let file = new Blob([content],{type:'text/html'});
let href = window.URL.createObjectURL(file);
let a = document.createElement('a');
a.href = href;
a.setAttribute('download', 'report.html');
document.body.appendChild(a);
a.dispatchEvent(new MouseEvent('click'));
}
Another problem is that you don't append your link into the DOM in the code you provided. So the DOM cannot trigger your mouse event and so starting the download (it's needed by some browsers).
With the good mime type, the file in a proper format and a link in to the dom, it should be ok.

New window and incorrect filename when saving data as CSV file

I am getting some CSV data from an Ajax request. I am trying to use FileSaver.js (https://github.com/eligrey/FileSaver.js/) to enable the end-user directly download this data as a CSV file.
This is the code used in my Ajax request handler.
jQuery.post(urlPrefix + "/api/ReportData",
dataToPost,
function (data, status) {
var blob = new Blob([data], { type: "text/csv" });
var fileName = "";
fileName += "Data-Export";
fileName += ".csv";
saveAs(blob, fileName);
});
This code is called from a button click event. Whenever the code executes, a new tab is opened, and the file is saved without a csv extension. In fact, the downloaded file has no extension at all. See the attached screenshot for details. The (7) is due to this being my seventh download.
The actual file that is saved is a valid file. If I manually set its extension to csv, I can use it properly. But I want to know how to use FileSaver to generate appropriate extension, and also download the file without opening a new tab.
What I have already tried
Export to CSV using jQuery and html
I found out this link https://code-maven.com/create-and-download-csv-with-javascript where it is possible to create a hidden anchor tag and download the file.
My new code is below
jQuery.post(urlPrefix + "/api/ReportData",
dataToPost,
function (data, status) {
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(data);
hiddenElement.target = '_blank';
hiddenElement.download = 'Exported-Data.csv';
hiddenElement.id = "customTemporaryAnchor";
hiddenElement.click();
jQuery("#customTemporaryAnchor").remove();
});
When this code is executed, the file downloads with proper extension, and without any popup or new tab.

How can I download a pdf from a url using javascript?

I need to download pdf's from one of our online resources.There is no built in function to batch download.The only way to do it is to navigate to each pdf file, click to open, then click download.
There are several thousand files and this would take a very long time to do.
I got around this in the past using javascript. I gathered all the links to the pdfs, put them in a csv, and had the code loop through each link, download, and move onto the next link.
Unfortunately, I have lost that code and my efforts to recreate it have been unsuccessful.
I have tried everything in this article: How to download PDF automatically using js?
I have tried the code from this article (which I'm pretty sure is what I did before): https://www.convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/
This is what I think should work...per the second article I referenced above
function download_file(fileURL, fileName) {
var link = document.createElement('a');
link.href = fileURL;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
}
var fileURL = "link/to/pdf";
var fileName = "test.pdf";
download(fileURL,fileName);
The code above is just to test download one file from a hardcoded URL. If it worked as intended, when the page is loaded, it should download the pdf from the provided url. Instead, it doesn't do anything on load or refresh.
Any suggestions?
Please check
https://stackoverflow.com/a/18983688/6923146
click me
Another one
https://stackoverflow.com/a/45905238/6923146
function download(url, filename) {
fetch(url).then(function(t) {
return t.blob().then((b)=>{
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
}
);
});
}
download("https://get.geojs.io/v1/ip/geo.json","geoip.json")
download("data:text/html,Hello Developer!", "HelloDeveloper.txt");
I hope it helpfull
https://www.convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/
You must add link element to DOM
function download_file(fileURL, fileName) {
var link = document.createElement('a');
link.href = fileURL;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
var fileURL = "https://cdn.sstatic.net/clc/img/jobs/bg-remote-header-sm.png";
var fileName = "test.pdf";
download_file(fileURL, fileName); // fix function name
Link must be in same origin
The download attribute on anchor was ignored because its href URL has a different security origin.

How to set delimiter while exporting html table to xls file, so that it won't ask for delimiter separately when opening file with openOffice calc?

Javascript code to generate xls file
// string to be obtained in xls file in different columns
var exportString = 'Source1; 240; A/V Signal drop out; 15';
// creating anchor tag
var a = document.createElement('a');
a.href = 'data:attachment/xls,' + exportString;
a.target = '_blank';
a.download = 'filename.xls';
document.body.appendChild(a);
a.click();
You may have different delimiters so you are probably not doing anything wrong open office just needs to know what should be used as delimiter.

Generate office open XML excel file from javascript

Is there a way to generate an .xslx file from javascript and allow the user to download it by javascript? This page is geared towards being run offline in html 5 with no internet connectivity.
You could generate a data URI, and let the user save the link. However, IE8 has very limited support for data URIs. There is a 32 KB limit, and it's not allowed to be used with a href.
Also, you still need to find a actual XLSX JS library... But it is possible.
It has been done successfully by Ed Spencer. This project is using an EXT DataGrid as the source of the data, but I'm sure you could adapt it pretty easily.
**Yes You Can do it using javascript**
** call function expexcel('table_id','output_file_name');**
<script>
function expexcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
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();
}
}
</script>
As Javascript has no file I/O, it's not going to be easy for your users to download. However, this kind of work is perfectly suited for a simple PHP script, which could generate your XSLX and save to your server dynamically.
You can generate any Office document with
OpenXML SDK for Javascript
http://openxmlsdkjs.codeplex.com/
As for allowing the user to save a file from JS I recommend FileSaver.js
https://github.com/eligrey/FileSaver.js/

Categories

Resources