Using ExcelBuilder.js with FileSaver.js - javascript

In my application I cant use Downloadify (which is recommended by ExcelBuilder.js) so I tried to download my .xlsx file with FileSaver.js
I tried both
var blob = new Blob([builder.createFile(basicReport.prepare())],{
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base65"
})
saveAs(blob, "myXLSX.xlsx");
and
var blob = new Blob([builder.createFile(basicReport.prepare())],{
type: "application/vnd.ms-excel;charset=charset=utf-8"
})
saveAs(blob, "myXLSX.xlsx");
I can download the file and i tried .xls and .xlsx extensions as well. The Excel cant open the .xlsx and if i try to open the .xls it opens but the data is uninterpretable.

Update 14-Sep-2017: there is a simpler code for this as you can see at https://github.com/eligrey/FileSaver.js/issues/262#issuecomment-256602092. You can remove the new Blob line and just use:
ExcelBuilder.Builder.createFile(workbook, {type:'blob'})
.then(function(blob) {
FileSaver.saveAs(blob, 'File.xlsx');
});
I was having the same issue today, but with the Angular version of FileSaver.js. And I solved it unintentionally. The following code just worked:
ExcelBuilder.Builder.createFile(workbook, {type:'blob'})
.then(function(blob) {
var data = new Blob([blob], {type:'base64'});
FileSaver.saveAs(data, 'File.xlsx');
});
My libraries "angular-file-saver": "1.1.2" and "excel-builder-js": "https://github.com/rodrigosaling/excel-builder.js.git#master" that is a fork of excel-builder.js#2.0.2.
Some clarifications (because it was not 100% unintentional):
the {type:'blob'} came from
https://github.com/stephenliberty/excel-builder.js/issues/4#issuecomment-54961321;
the createFile() returns a promise and not a file (without the then() the library will create a file containing a "Promise" text on the first cell);
my fork of the library is to replace the generate() by generateAsync() on JSZip library. generate() was replaced on v3 that is the version ExcelBuilder requests;
why the {type:'base64'}? It's only a guess, but I think is what an Excel file is after its content is zipped. I don't know.

I couldnt make it with fileSaver.js library so I made a link in my event handler, clicked it and then removed the link.
var myA = document.createElement('a');
myA.setAttribute('href', "'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + EB.createFile(workbook));
myA.setAttribute('download', "myXLSX.xlsx");
document.getElementById("mydiv").appendChild(myA);
myA.click();
document.getElementById("mydiv").removeChild(myA);

Related

Print file on client side

I am using FileSaver.js to print an object array on the client side (HTML/Typescript).
var blob = new Blob([JSON.stringify( marray)], {type: "text/plain;charset=utf-8"});
saveAs(blob, "Data.txt");
It works fine. The problem is it downloads in the download folder (by default). I want to add a file path along with its name. Any idea? Or another way to do this job. fs is not working in this case. it is not recognizing fs and gives the error fs.writefilesync is not a function
How do you know what path the user has?
It is not safe. There is no way to "climb" the user's file system
If you open the source code, you will see the simplest implementation scheme there. It's just a click on a link download
var a = document.createElement('a')
// ...
a.href = blob
// ...
a.dispatchEvent(new MouseEvent('click'))

Excel downloaded using window.saveAs() is not opening

I'm developing and application that has node.js at backend and Angular.js in front end. I'm using exceljs module in node to create a xlsx book. UI is making ajax call to download xlsx file.
Node.js code.
response.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
response.setHeader("Content-Disposition", "attachment; filename=" + quoteId +".xlsx");
workbook.xlsx.write(response).then(function () {
response.end();
});
Angular code
DownloadService.downloadServiceCall(inputParam).then(
function success(res){
var blob = new Blob([res.data], { type: res.headers()['content-type'] });
var header = res.headers()['content-disposition'];
var fileName = header.match(/filename=(.+)/)[1];
window.saveAs(blob,fileName);
});
I'm able to download csv file and open it with above code.
Excel file is getting downloaded but I'm unable to open the same. It throws following error
Anyone have an idea about this issue, please suggest the solution. Any help on this would be appreciated.
Thanks..
It was due to async call from Angular. Has nothing to do with saveAs. Added responseType:'arraybuffer' in the request object. It resolved the issue.
$http({method:'get',url:'',responseType:'arraybuffer'})

How to download a file generated with JavaScript, avoiding automatic opening of Chome?

I am developing a JavaScript little webmail.
I receive from the server a Base64-encoded string, that represents a file (it could be whatever type). I decode the string, a map it to a Uint8Array, and with it, I generate a Blob object with I create a data URI with
FileReader.readAsDataURL(blob)
Until here is pretty straightforward, but I am having problem with the download part.
I put the DataURI in
window.open(dataURI)
But chrome opens a new window and display my image, or my text. But I need to avoid this behaviour, and download the file instead.
I have red that this could be done with Content-Disposition "attachment" but I am not sure if it is my case, because I am generating the file from a string from the server.
Anyone who can help me understand?
Did you try to use "saveAs" ?
saveAs(blob, "hello.zip");
In the case you need wide browser support you could try polifill. More information
I am pretty sure you can set the type of the blob
var blob = new Blob(["Hello world!"], { type: "application/download" });
Edit:
without FileSaver.js:
var blob = new Blob(["Hi stack"], {type: 'application/download'});
var reader = new FileReader();
reader.onloadend = function(e) {
window.open(reader.result);
}
reader.readAsDataURL(blob);
Edit:
Documentation and browser support information ("Browser compatibility" tab):
FileReader
Blob

encodeURI file download - crashing browser

I created a web application to clean up CSV/TSV data. The app allows me to upload a CSV file, read it, fix data, and then download a new CSV file with the correct data. One challenge I have run into is downloading files with more than ~ 2500 lines. The browser crashes with the following error message:
"Aw, Snap! Something went wrong while displaying this webpage..."
To work around this I have changed the programming to download multiple CSV files not exceeding 2500 lines until all the data is downloaded. I would then put together the downloaded CSV files into a final file. That's not the solution I am looking for. Working with files of well over 100,000 lines, I need to download all contents in 1 file, and not 40. I also need a front-end solution.
Following is the code for downloading the CSV file. I am creating a hidden link, encoding the contents of data array (each element has 1000 lines) and creating the path for the hidden link. I then trigger a click on the link to start the download.
var startDownload = function (data){
var hiddenElement = document.createElement('a');
var path = 'data:attachment/tsv,';
for (i=0;i<data.length;i++){
path += encodeURI(data[i]);
}
hiddenElement.href = path;
hiddenElement.target = '_blank';
hiddenElement.download = 'result.tsv';
hiddenElement.click();
}
In my case the above process works for ~ 2500 lines at a time. If I attempt to download bigger files, the browser crashes. What am I doing wrong, and how can I download bigger files without crashing the browser? The file that is crashing the browser has (12,000 rows by 48 columns)
p.s. I am doing all of this in Google Chrome, which allows for file upload. So the solution should work in Chrome.
I've experienced this problem before and the solution I found was to use Blobs to download the CSV. Essentially, you turn the csv data into a Blob, then use the URL API to create a URL to use in the link, eg:
var blob = new Blob([data], { type: 'text/csv' });
var hiddenElement = document.createElement('a');
hiddenElement.href = window.URL.createObjectURL(blob);
Blobs aren't supported in IE9, but if you just need Chrome support you should be fine.
I also faced same problem. I used this code,it will works fine. You can also try this.
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(new Blob([base64toBlob($.base64.encode(excelFile), 'text/csv')]),'data.csv');
} else {
var link = document.createElement('a');
link.download = 'data.csv';
// If u use chrome u can use webkitURL in place of URL
link.href = window.URL.createObjectURL(new Blob([base64toBlob($.base64.encode(excelFile), 'text/csv')]));
link.click();
}

How can i generate a file and offer it for download in plain javascript?

I would like to generate a text file in the javascript dynamicly, then offer this for download. Currently I can get this working to a degree with either of the following solutions:
content = "abc123";
document.location = "data:text/octet-stream," + encodeURIComponent(content);
OR
content = "abc123";
var bb = new BlobBuilder();
bb.append(content);
var blob = bb.getBlob();
blob = blob.slice(0, blob.size, 'text/octet-stream');
var fr = new FileReader();
fr.onload = function() {document.location = this.result;}
fr.readAsDataURL(blob);
However, Both of these solutions, when the download box appears, will only offer a default filename of 'download' in the save as dialogue.
My question is basically, how can I change this to a specific filename for example 'readme.txt' or 'scene.obj'
Also note the data type was previously 'text/plain' however if this is used, the document switches to the new text document instead of offering it for download (as text/octet-stream seems to do).
I do not want a flash solution, javascript/html5 only suggestions please.
Cheers, Josh
For that, you will have to use FileSaver from FileAPI: Writer specification.
For now, it's only a draft, and according to mailing list answer it isn't yet implemented in browsers.
You can watch for example on a chromium issue to get up-to-date information about the implementation progress
UPD 02.08.2013: I have since found a project that provides FileSaver interface using neat tricks
I think you should check: jQuery Table to CSV export

Categories