Export AngularJS table to .CSV directing to about:blank page? - javascript

I currently have a Javascript function which exports my AngularJS table of JSON data to a .csv file by div ID as shown:
$scope.exportToExcel = function (tableId) { // ex: '#my-table'
var exportHref = Excel.tableToExcel(tableId, 'WireWorkbenchDataExport');
$timeout(function () { location.href = exportHref; }, 100); // trigger download
}
Which I call like so
<button style="float: right;" class="btn btn-link" ng-click="exportToExcel('#codeProjectsTable')" filename="test.csv">
<span class="glyphicon glyphicon-share"></span>
Export table
</button>
This works well for data sets with ~400 records or less (20 columns per record), but I'm trying to export nearly 1,000 records for further reporting and I am simply being directed to an about:blank page.
I'm suspecting that it is either
Unable to export this large of a file
Timing out because of a long request
Thanks in advance.

I used following logic for to export
var fileName = 'users_export_' + moment().format('YYYY-MM-DD') + '.csv';
var url = URL.createObjectURL(new Blob([response.data]));
var a = document.createElement('a');
a.href = url;
a.download = fileName;
a.target = '_blank';
a.click();
And its working for large for large file/data

Related

How to make attachment downloadable - Angular

I have a scenario where user can upload files (PDF/PNG) and show if any files are already uploaded. I'm able to do Uploading part and showing the user any files are already uploaded. Now I want the user can download if any uploaded files are present on clicking on the attachment. Could you guys advise?
ts file
upload() {
const fileUpload = this.fileUpload.nativeElement; //* retrieve native DOM element wrapped by ElementRef
fileUpload.onchange = () => {
const file = fileUpload.files[0]; // retrieve file
if (file) {
const filesize = getFileSizeHelper(file.size); // get file size
if (filesize <= 2) {
this.filename = file.name;
this.uploadFile(file);
} else {
this.fileSizeEr.emit(true);
}
}
};
fileUpload.click(); // open file picker window
}
/**
* method to upload file
*/
uploadFile(file: any) {
const formData = new FormData();
formData.append('file', file, file.name);
this.myservice.uploadFile(formData).subscribe((res: any) => {
this.uploadedFile = res;
this.fileUploadRes.emit(res); //emit response object to parent component
});
}
HTML file
<div class="upload-space" (click)="upload()">
<mat-icon *ngIf="!doc?.fileName">publish</mat-icon>
<span *ngIf="!doc?.fileName">
{{ "PNG and PDF files allowed(max.2MB)" | translate }}
</span>
<span *ngIf="doc?.fileName">
{{ doc.fileName }}
</span>
<!-- <span *ngIf="filename">
{{ filename }}
</span>-->
<input
type="file"
#fileUpload
id=""
name="fileUpload"
accept="image/*,application/pdf"
style="display:none;"
/>
</div>
I assume you are using blob, so after you created a link, with or without class="button", you should simply bind a function on (click) event with some identification property, and get it from your server, then, tell your httpget that the response type is blob.
With angular httpclient looks something like this:
//injected httpService from angular
this.httpClient.get('your controller', { responseType: blob}).subscribe( response => {
const a = document.createElement('a'); // get the element
const objectUrl = URL.createObjectURL(response); //create objecturl
a.href = objectUrl; //make the <a></a> link's href to this object url
a.download = 'any name you want to add';
a.click(); //imitate a click on it
//THE FOLLOWING STATEMENT IS ONLY FOR BE ABLE TO DOWNLOAD IT IN MS EDGE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(response, 'any name you want to add' + ".pdf");
}
URL.revokeObjectURL(objectUrl);
})
I think its not the perfect solution, but it worked for me.

Export to excel with images in JavaScript

I have the following code :
<button id="myButtonControlID" onclick="ExcelExport();">Export to Excel</button>
<script>
function ExcelExport(){
var imgurl = "https://image.flaticon.com/icons/svg/60/60752.svg"
var HTMLtext="<table><tr><td>Image export</td><td><img src='"+imgurl+"'style='width:500px;height:600px;'></img></td></tr></table>";
window.location.href = 'data:application/vnd.ms-excel,' + encodeURIComponent(HTMLtext);
sa = window.location.href;
return (sa);
}
</script>
With this I am able to export an excel file as XLS but since the image is a link,it is only displayed when I am connected to the internet. Is there a way to embed the image to excel in such a way that the image is not a link and it is displayed even when you are offline?

Javascript export local storage

I have this piece of code on a site that exports the contents of local storage to a file in JSON format.
For some reason it stopped working. I tested it in multiple browsers but it's all the same...
No errors get displayed, yet it doesn't export either.
The different variables seem fine, yet it just isn't exporting.
To be honest I have no clue how to do this differently so any help would be appreciated.
Thx
function exportHistory() {
console.log("started");
var _myArray = JSON.stringify(localStorage , null, 4); //indentation in json format, human readable
var vLink = document.getElementById('exportHistory'),
var vBlob = new Blob([_myArray], {type: "octet/stream"}),
vName = 'working_history_' + todayDate() + '.json',
vUrl = window.URL.createObjectURL(vBlob);
console.log(vLink);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
console.log("finished");
}
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >
Here you need to add the download attribute to an anchor tag <a> rather than the clicking button itself. You need to create an anchor tag with display:none and programmatically click it to download the file. Here is an example. Notice the button only used to execute the function and href and download attributes are added to the <a> tag.
function exportHistory() {
console.log("started");
var _myArray = JSON.stringify(localStorage , null, 4); //indentation in json format, human readable
//Note: We use the anchor tag here instead button.
var vLink = document.getElementById('exportHistoryLink');
var vBlob = new Blob([_myArray], {type: "octet/stream"});
vName = 'working_history_' + todayDate() + '.json';
vUrl = window.URL.createObjectURL(vBlob);
console.log(vLink);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
//Note: Programmatically click the link to download the file
vLink.click();
console.log("finished");
}
Now add an empty anchor tag to the DOM.
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >
<a id="exportHistoryLink" style="display: none;">Export</a>

Download a file from a link on button value

I searched a lot but couldn't find a solution I thank anyone who can help me.
I want to download files on button click but based on values in the text of buttons.
I have three buttons in my HTML like this
<input type="button" onclick="myFunction(this, name1.mp3)" value="button1.mp3">
<input type="button" onclick="myFunction(this, name2.mp3)" value="button2.mp3">
<input type="button" onclick="myFunction(this, name3.mp3)" value="button3.mp3">
my JavaScript is
function myFunction(elmnt, name) {
var url = "http://mysite*com/" + elmnt.value;
var downloadFileWithThisName = name;
---my download code---
}
How can I download my url with the name I passed to function?
what should I write for ---my download code--- part?
Thank you in advance.
function myFunction(elmnt, name) {
var url = "http://mysite*com/" + elmnt.value;
const a = document.createElement('a');
a.href = url;
a.download = name; // here you can specify your filename
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
What you could do is to dynamically create an A element, add the 'download' attribute, set the Href and click it, all in code. Then remove it from the DOM.
The best answer judging for your code is shown here: https://stackoverflow.com/a/42696866/1891140
var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
But you also can do it by using a simple JQUERY:
$("<a href='"+url+"' download class='hidden-a'></a>").appendTo("body");
$(".hidden-a")[0].click();

How to add Comment in CSV Header using JavaScript/JQuery

I want to add a comment on Header fields of CSV File generated by Javascript
Also, I have Searched out for these requirements but can't find any solutions
Here is code that's using for generating CSV File using Javascript
var data = [
['123'],
['346'],
['789'],
['Test1'],
['Test2']
];
function download_csv() {
var csv = 'ID\n';
data.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
console.log(csv);
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'test.csv';
document.getElementById('container').appendChild(hiddenElement);
hiddenElement.click();
}
<button onclick="download_csv()">Download CSV</button>
<div id="container" style="display:none;"></div>
I want to Add Header Comment like Here
There is no standard way to achieve this using CSV. However, you can resort to writing the file as XLXS as commenting is an application specific feature.

Categories