Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Export HTML table to Excel in AngularJS

Export HTML table to Excel in AngularJS

myApp.factory('Excel',function($window){
		var uri='data:application/vnd.ms-excel;base64,',
			template='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
			base64=function(s){return $window.btoa(unescape(encodeURIComponent(s)));},
			format=function(s,c){return s.replace(/{(\w+)}/g,function(m,p){return c[p];})};
		return {
			tableToExcel:function(tableId,worksheetName){
				var table=$(tableId),
					ctx={worksheet:worksheetName,table:table.html()},
					href=uri+base64(format(template,ctx));
				return href;
			}
		};
	})
	.controller('MyCtrl',function(Excel,$timeout){
	  $scope.exportToExcel=function(tableId){ // ex: '#my-table'
			$scope.exportHref=Excel.tableToExcel(tableId,'sheet name');
			$timeout(function(){location.href=$scope.fileData.exportHref;},100); // trigger download
		}
	});

How to use:

	<button class="btn btn-link" ng-click="exportToExcel('#table1')">
		<span class="glyphicon glyphicon-share"></span> Export to Excel
	</button>
@kevjose

This comment has been minimized.

Copy link

kevjose commented Apr 16, 2015

thanks for the snippet ..
Can you make similar one for pdf also ?
i tried with var uri='data:application/pdf;base64,',
but it shows failed to load document error

@villian

This comment has been minimized.

Copy link

villian commented Apr 20, 2015

Thanks,
Great Directive, but we have error when trying to open our file via google spreadsheets:

http://screencast.com/t/qoa8XVPBsFm

Thanks

@YassIkrou

This comment has been minimized.

Copy link

YassIkrou commented Apr 21, 2015

Very useful, thank you;
can you please tell me how to solve encodage problems (for example displaying 'é' because it is not displaying correctly), and what if I had inputs inside f my ?? it is not displaying correctly.

@dongminkim

This comment has been minimized.

Copy link

dongminkim commented May 13, 2015

Thanks!
With fixing a small bug, it works greatly.

      $scope.exportToExcel=function(tableId){ // ex: '#my-table'
            var exportHref=Excel.tableToExcel(tableId,'sheet name');
            $timeout(function(){location.href=exportHref;},100); // trigger download
        }
@SamirMatkar

This comment has been minimized.

Copy link

SamirMatkar commented May 21, 2015

@SamirMatkar

This comment has been minimized.

Copy link

SamirMatkar commented May 21, 2015

Hi
I am able to resolve the above issue.

but now getting exception when this line execute
$timeout(function () { location.href = $scope.fileData.exportHref; }, 100);

at Anonymous function (http://localhost:10133/app/15WindowExample/windowcontroller.js:27:33)
at Anonymous function (http://localhost:10133/scripts/angular/angular.js:14276:11)
at completeOutstandingRequest (http://localhost:10133/scripts/angular/angular.js:4397:7)
at Anonymous function (http://localhost:10133/scripts/angular/angular.js:4698:7)

any idea what is causing this ?

@sandeepthukral

This comment has been minimized.

Copy link

sandeepthukral commented May 27, 2015

@SamirMatkar , I am getting the same error '$' is undefined. How did you resolve this issue?

@sandeepthukral

This comment has been minimized.

Copy link

sandeepthukral commented May 28, 2015

I got this working fully. I only needed to include jQuery in my code. I used 1.9.0. After this, it worked like a charm.
I had earlier tried to work with JavaScript's document.querySelector but then there was no way to get a replacement of the .html() function on it.

@SamirMatkar

This comment has been minimized.

Copy link

SamirMatkar commented Jun 2, 2015

Hi ,
I also got this working with BUT Only in Chrome with jquery-1.8.3.version. and not working in IE (10).
Now do I have to apply the traditional approach of Excel object creation to implement export for IE browser. or there is better way of doing in IE.
Please advise, Thanks in advance

@Sebash93

This comment has been minimized.

Copy link

Sebash93 commented Jun 4, 2015

I got it working without JQuery changing the last part of the factory code to this:

return {
    tableToExcel:function(tableId,worksheetName){
        var table=document.querySelector(tableId),
            ctx={worksheet:worksheetName,table:table.innerHTML},
            href=uri+base64(format(template,ctx));
        return href;
    }
};
@neovldz

This comment has been minimized.

Copy link

neovldz commented Jun 4, 2015

Is there a way to give a custom name to the xls file?

@Fabio1986

This comment has been minimized.

Copy link

Fabio1986 commented Jun 5, 2015

Why is downloading a file called: "download" with no extension, using exactly the same code ?

@qhuy

This comment has been minimized.

Copy link

qhuy commented Jul 7, 2015

Thanks for the directive.
i try to open the file in Drive Google, error detected

BTW, my trick to give a custom name to the xls file:
$scope.exportHref = excel.tableToExcel(tableId, 'sheet name');
$timeout(function() {
var link = document.createElement('a');
link.download = "export.xlsx";
link.href = $scope.exportHref;
link.click();
}, 100);

@asohank

This comment has been minimized.

Copy link

asohank commented Jul 11, 2015

New to AngularJS.
Am trying export list of data to excel using above sample. but iam getting error.
"May I have to add any js file"

ReferenceError: Excel is not defined
at k.$scope.exportToExcel (PhoneNotFoundCtrl.js:32)
at angular.js:10847
at f (angular.js:19136)
at k.$eval (angular.js:12702)
at k.$apply (angular.js:12800)
at HTMLButtonElement. (angular.js:19141)
at HTMLButtonElement.m.event.dispatch (jquery-1.11.1.min.js:3)
at HTMLButtonElement.r.handle (jquery-1.11.1.min.js:3)

@FraGoTe

This comment has been minimized.

Copy link

FraGoTe commented Jul 13, 2015

@asohank you should add it as this example

.controller('MyCtrl',function(Excel,$timeout){
});

@SherryXun

This comment has been minimized.

Copy link

SherryXun commented Jul 20, 2015

I want to ask whether the table export to xlsx file,and define the file name byself

After download the file ,the excel file reader throw this error:Excel 无法打开“”文件,因为文件格式和文件扩展名无效。请确定文件为损坏,并且文件的扩展名与文件格式匹配

@destanoglu

This comment has been minimized.

Copy link

destanoglu commented Sep 10, 2015

Thank you for the code, its working just fine. But the result excel file shows a warning at the begining:
"... the file could be corrupted or unsafe... "
Do you know the solution?

@sayanbanerjee87

This comment has been minimized.

Copy link

sayanbanerjee87 commented Oct 11, 2015

After downloading the file it is giving different format warning message, is there any solution available for that??

@iprospectnorway

This comment has been minimized.

Copy link

iprospectnorway commented Oct 21, 2015

Hi! I am trying to get this to work.. I've put my controller in a script for itself and the main app script in another. Everything is working fine with populating the table, but I cannot seem to get the export to work. I get "TypeError: Cannot read property 'exportHref' of undefined" in the console.

@vijaybisht34

This comment has been minimized.

Copy link

vijaybisht34 commented Nov 3, 2015

only getting data of first page...please suggest how to get the data of all the pages

@MubinShaikh

This comment has been minimized.

Copy link

MubinShaikh commented Nov 9, 2015

I am unable to Export table in IE.Gide me for Same

@VeeramaniBagavathi

This comment has been minimized.

Copy link

VeeramaniBagavathi commented Nov 26, 2015

I too tried in IE11. it is not downloading. Firefox it is working fine.

Factory:
app.factory('Excel',function($window){
var uri='data:application/vnd.ms-excel;base64,',
template='

{table}
',
base64=function(s){return $window.btoa(unescape(encodeURIComponent(s)));},
format=function(s,c){return s.replace(/{(\w+)}/g,function(m,p){return c[p];})};
return {
tableToExcel:function(tableId,worksheetName){
var table=$(tableId),
ctx={worksheet:worksheetName,table:table.html()},
href=uri+base64(format(template,ctx));
return href;
}
};
})

Controller method:

$scope.exportToExcel = function(tableId) {
var exportHref=Excel.tableToExcel(tableId,'sheet name');
$timeout(function(){location.href=exportHref;},100); // trigger download
};

HTML:

Export Table data into Excel










ColumnOne tesColumnTwo
row1ColValue1row1ColValue2
row2ColValue1row2ColValue2


Error in line:
line 28 : $timeout(function(){location.href=exportHref;},100); // trigger download

Error in IE11 Console:
at Anonymous function (file:///D:/AngularTryOuts/MultipleLinks/js/controller.js:28:22)
at Anonymous function (file:///D:/AngularTryOuts/MultipleLinks/js/framework/angular.js:14305:11)
at completeOutstandingRequest (file:///D:/AngularTryOuts/MultipleLinks/js/framework/angular.js:4397:7)
at Anonymous function (file:///D:/AngularTryOuts/MultipleLinks/js/framework/angular.js:4705:7)

@harikanukala

This comment has been minimized.

Copy link

harikanukala commented Dec 3, 2015

There is no application set to open the URL data:application/vnd.ms-excel;base64,......
I am getting this pop-up when i tried to use this directive..I am using mac.... help me !!

@ironmanLee

This comment has been minimized.

Copy link

ironmanLee commented Dec 7, 2015

Thank you very much for the solution...
It works great on Chrome.

But it does not work on IE11.
My client insist on using IE only.
Would you please help me?

Error message on IE11 is as follows.

Error
at Anonymous function (http://localhost:8090/index.html:145:39)
at Anonymous function (http://localhost:8090/common/angular.min.js:110:175)
at e (http://localhost:8090/common/angular.min.js:33:514)
at Anonymous function (http://localhost:8090/common/angular.min.js:37:173)

@romanvieito

This comment has been minimized.

Copy link

romanvieito commented Dec 21, 2015

Didn't work for 10000 rows...solution?

@L3g4to

This comment has been minimized.

Copy link

L3g4to commented Jan 28, 2016

Seems not to work on some browsers :(. Was easier to do it directly from Excel with an Excel AddIn

@CliffyMk

This comment has been minimized.

Copy link

CliffyMk commented Feb 4, 2016

Here's a working Demo

@sunilkumarkota

This comment has been minimized.

Copy link

sunilkumarkota commented Feb 8, 2016

Solution for "TypeError: Cannot read property 'exportHref' of undefined" in the console:
Remove fileData from $scope.fileData.exportHref....through out program we didn't use fileData anywhere....so please remove it and njoy...its working great.....

@msenthu

This comment has been minimized.

Copy link

msenthu commented Feb 18, 2016

I have problem loading large content into excel. I have 1500 rows or if I do an view source the number lines on the table content is 25000 lines. With this number of lines its not exporting to excel. But if I reduce to few rows then it works perfectly. Is there any setting I need to change?

would you please help me resolve this?

@onlythinking

This comment has been minimized.

Copy link

onlythinking commented Mar 1, 2016

Great Directive

@ghost

This comment has been minimized.

Copy link

ghost commented Mar 8, 2016

It works great on Chrome.

But it does not work on IE11.
Would you please help me?

@ritika861

This comment has been minimized.

Copy link

ritika861 commented Mar 16, 2016

I am able to use this code. But when i click on export to excel, it open excel with a warning message that xsl is not in correct format. The file could be corrupt or unsafe. Do you want to open it.
Can anyone help me resolving this. And if there's no resolution with this plugin. Is there any other plugin that I can leverage for export to excel functionality. I need to export html table which has pagination.
Thanks in advance.

@sayhi2sam

This comment has been minimized.

Copy link

sayhi2sam commented Apr 11, 2016

Helps you with a custom file name for the downloaded table

$scope.exportToExcel=function(tableId){
var exportHref=Excel.tableToExcel(tableId,'report');
var a = document.createElement('a');
a.href = exportHref;
a.download = 'Exported_Table.xls';
a.click();
}

@IDCOLL

This comment has been minimized.

Copy link

IDCOLL commented Apr 30, 2016

Hi,
I am trying to refactor this directive into a component style angularjs template. Please see my full question and progress thusfar here:
http://stackoverflow.com/questions/36961034/refactoring-factory-controller-into-component-style-angularjs

Any assistance would be appreciated!

@Tyna09

This comment has been minimized.

Copy link

Tyna09 commented May 18, 2016

Thank you very much for your code!

To display 'é,á,ä ...' characters help this, when you add to template:
meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
image

@sunandanbarman

This comment has been minimized.

Copy link

sunandanbarman commented Jul 14, 2016

For the code provided by @sayhi2sam , I was getting "file corrupted". I just changed the extension to .xls instead of .xlsx. That solved the issue for me.

@mauscoelho

This comment has been minimized.

Copy link

mauscoelho commented Jul 21, 2016

@Tyna09 thank you very much to encoding

@ansaridawood

This comment has been minimized.

Copy link

ansaridawood commented Aug 19, 2016

with the help of @dongminkim, its works great in chrome, but it does not work in Internet Explorer 11, it just redirect to new blank page with url like data:application/vnd.ms-excel;base64,PGh0bWwgeG1sbnM6bz...
any idea to fix it?

@Nahiduzzaman

This comment has been minimized.

Copy link

Nahiduzzaman commented Sep 18, 2016

How can i export whole table data when my table is paginated? I can export every single page but cant export data of all pages at once.

@hryogesh

This comment has been minimized.

Copy link

hryogesh commented Sep 28, 2016

Hi @Nahiduzzaman

If you have crated the pagination in angular using this library dirPagination.js : https://github.com/rahil471/search-sort-and-pagination-angularjs/blob/master/lib/dirPagination.js

replicate the same table with ng-repeat instead of dir-paginate & made table display none .. give this table to export to excel.

@hryogesh

This comment has been minimized.

Copy link

hryogesh commented Sep 28, 2016

Export to excel not working on IE 11,

Please any solution for IE 11

@sangram210

This comment has been minimized.

Copy link

sangram210 commented Oct 5, 2016

Export to excel not working on IE .
Please provide any solution for IE browser.

@Jigar911

This comment has been minimized.

Copy link

Jigar911 commented Oct 19, 2016

Hi ,

I wish to have "Export excel" feature for the Div without a table however with the GridContent that has tabular data.
I used above code however it displays all my tabular data in the first column instead of tabular format.
Any suggestion would be highly appreciated.

@amit03wit

This comment has been minimized.

Copy link

amit03wit commented Oct 25, 2016

How to remove specific HTML from excel ? When I'm trying to export it fetches check boxes and drop-down without value. how can i restrict and display only selected drop-down value in Excel ?

 <td >
                                            <select class="form-control"   ng-model="customer.qa" ng-change="CustomerEnquiry(custList.CustomertId)">
                                                <option ng-repeat="item in lstCustomers" value="{{item.customerId}}">{{item.custName}}</option>
                                            </select> 

                                        </td>

capture

@byWeaponLin

This comment has been minimized.

Copy link

byWeaponLin commented Nov 5, 2016

Are you kidding me? Your source code is not correct.
Change the $scope.fileData.exportHref to $scope.exportHref.

@victorhazbun

This comment has been minimized.

Copy link

victorhazbun commented Nov 29, 2016

FUCK YOU WITH YOUR SCRIPT IT DOES NOT WORK, YOU ARE DOWNLOADING HTML. DUMB ASS.

@allenz0810

This comment has been minimized.

Copy link

allenz0810 commented Nov 30, 2016

for some reason, even though i pass in the worksheet name it still give me download.xls.

var exportHref = Excel.tableToExcel(tableId, "ExchangeData " + new Date().getDate());

@mansoorsm

This comment has been minimized.

Copy link

mansoorsm commented Dec 1, 2016

Hi can any body help me that i am using ng-repeat for one row and its is giving me data in excel sheet at second click of the button only please any body can answer its very urgent????????????

@MarkVilludo

This comment has been minimized.

Copy link

MarkVilludo commented Dec 5, 2016

dongminkim thanks. It works on me. Cheers!

@ghost

This comment has been minimized.

Copy link

ghost commented Dec 6, 2016

thank you ! For IE and change the name of your file change this part :

`return {
getExportExcel: function (tableId, fileName) {

            name = fileName + '.xls';
            var table = document.querySelector(tableId),
                ctx = {table: table.innerHTML};
            var browser = window.navigator.appVersion;

            if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) ||
                (browser.indexOf('MSIE 10') !== -1)) {
                var builder = new window.MSBlobBuilder();
                builder.append(uri + format(template, ctx));
                var blob = builder.getBlob('data:application/vnd.ms-excel');
                window.navigator.sSaveOrOpenBlob(blob, name);

            } else {

                var link = document.createElement('a');
                link.download = name;
                link.href = uri + base64(format(template, ctx));
                link.click();
            }
        }
    }`
@ahwyX100

This comment has been minimized.

Copy link

ahwyX100 commented Dec 8, 2016

Does anyone know how to create multi worksheet?

@jarodrigues

This comment has been minimized.

Copy link

jarodrigues commented Mar 3, 2017

Hi guys. I have a problem, when importing xls, I get utf-8 error. Special character, Any ideas?

@narender56

This comment has been minimized.

Copy link

narender56 commented Mar 10, 2017

It's not working in mozila firefox, it is downloading as with anonymous name and extension . How to customize it?. The code which is suggested by @sayhi2sam is not working in mozila firefox.

Please help.

@shreeshagundmi

This comment has been minimized.

Copy link

shreeshagundmi commented Mar 16, 2017

Hi geeks,
I have HTML table with Image and Audio file which is writen in Angularjs,
When i export the table to excel, all data in HTML will be exported to excel,

If image is there in table i need to replace that in to text. Please find the Attached images bellow

Table in HTML

capture

Table when i exported to Excel

imagetable

I need to replace the Table Like this when i export to Excel File

tablenoimage

Can any body please suggest me the solution?

@prasanthiperimena

This comment has been minimized.

Copy link

prasanthiperimena commented Apr 6, 2017

$scope.exportToExcel=function(tableId){
var exportHref=Excel.tableToExcel(tableId,'report');
var a = document.createElement('a');
a.href = exportHref;
a.download = 'Exported_Table.xls';
a.click();
}

After using the above code ,I am getting warning message before opening the file saying "The file could be uncorrupted or unsafe,Unless you trust its source, don't open it. Do you want to open it anyway"?
If I m clicking on yes, file is getting opened.
Can any one please help me, how to resolve this warning message before opening the file

@valeriopisapia

This comment has been minimized.

Copy link

valeriopisapia commented May 10, 2017

I have the same problem of @prasanthiperimena.
Any feedbacks?

@aayushpatidar

This comment has been minimized.

Copy link

aayushpatidar commented Jul 11, 2017

This is working great in Chrome but not in Internet Explorer and Microsoft Edge. It is also not working in MAC OS. Please resolve the issue as soon as possible.

@BarryPiccinni

This comment has been minimized.

Copy link

BarryPiccinni commented Jul 13, 2017

Hi, this works very well, but I'm having trouble getting it to work for larger tables. It works perfectly up to about 2100 rows. Any bigger and the download fails. Any thoughts on how to get around this?

@sandeepacharya93

This comment has been minimized.

Copy link

sandeepacharya93 commented Aug 11, 2017

@CliffyMk ,
Your code works after including id in table instead of div .
eg:

Instead of
.
and if the downloaded file doesnt open in apache open office just try changing extension name of your file to .xls

@ashokbabumiriyala

This comment has been minimized.

Copy link

ashokbabumiriyala commented Aug 29, 2017

it's working fine with chrome but IE it's not working.
suggest me any one why it's not working.

here is my code

   var uri = 'data:application/vnd.ms-excel;base64,',
           template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
           base64 = function (s) { return $window.btoa(unescape(encodeURIComponent(s))); },
           format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };
        var exportHref = tableToExcel($("#tbl_pcmreport"), $("#rptName"));
        function tableToExcel(tableId, worksheetName) {
                var table = $(tableId),
                    ctx = { worksheet: worksheetName, table: table.html() },
                    href = uri + base64(format(template, ctx));
                return href;
           }                     
        $timeout(function () { location.href = exportHref; }, 100); 
@VanarajV

This comment has been minimized.

Copy link

VanarajV commented Oct 16, 2017

For IE please replace with window.navigator.msSaveOrOpenBlob(blob, name);

@Anirudhk94

This comment has been minimized.

Copy link

Anirudhk94 commented Oct 20, 2017

Hi,

I want to export a table into xls. The size of the file is around 4MB - 5MB.
The script works fine in Firefox. But in Chrome, the export to excel button is redirecting me to about:blank page.

Any idea why?

@Anil-bohorya

This comment has been minimized.

Copy link

Anil-bohorya commented Jan 15, 2018

getting issue: -

  1. 'The file format and extension of 'abc.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?' while opening downloaded file.
  2. Background is totally white. Not showing grids with black border. Do I need to give styling inside code?

Please help.

@foyzulkarim

This comment has been minimized.

Copy link

foyzulkarim commented Jan 24, 2018

working code snippet (use raw javascript instead of jquery)

tableToExcel: function (tableId, worksheetName) { var table = document.getElementById(tableId); var ctx = { worksheet: worksheetName, table: table.innerHTML }; var href = uri + base64(format(template, ctx)); return href; }

but thanks for the snippet.

@emanzuetaj

This comment has been minimized.

Copy link

emanzuetaj commented Feb 2, 2018

AngularJS working version with all of the above

    angular
        .module('app')
        .factory('excel', ['$window', '$document', function($window, $document) {
            var uri = 'data:application/vnd.ms-excel;base64,';
            var template =
                '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
            var base64 = function(s) { return $window.btoa(unescape(encodeURIComponent(s))); };
            var format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }); };
            return {
                tableToExcel: function(tableId, worksheetName, fileName) {
                    var table = angular.element($document[0].getElementById(tableId));
                    var ctx = { worksheet: worksheetName, table: table.html() };
                    var browser = window.navigator.appVersion;
                    if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) ||
                        (browser.indexOf('MSIE 10') !== -1)) {
                        var builder = new window.MSBlobBuilder();
                        builder.append(uri + format(template, ctx));
                        var blob = builder.getBlob('data:application/vnd.ms-excel');
                        window.navigator.msSaveOrOpenBlob(blob, fileName);
                    } else {
                        var link = $document[0].createElement('a');
                        link.download = fileName;
                        link.href = uri + base64(format(template, ctx));
                        link.click();
                    }
                }
            };
        }]);

Can anyone tell me if there's a way to get rid of the security pop up? It's Microsoft's desired behavior per this post

Anyone able to get custom CSS working for this solution?
Update: answering my own CSS question... CSS must be inline for it to persist

@ankitpachori

This comment has been minimized.

Copy link

ankitpachori commented Feb 6, 2018

Dropdowns are also coming in the excel sheet,which is not expected..........

Can anyone guide me on this

@neerajchhatani

This comment has been minimized.

Copy link

neerajchhatani commented Feb 6, 2018

Dropdowns are also coming in the excel sheet,which is not expected..........

Can anyone guide me on this

@rahiakela

This comment has been minimized.

Copy link

rahiakela commented Feb 7, 2018

HI,
Could you give me some reference of html template for Excel that you have used above example. So that I can customise it according to my requirement.

Thanks

@vamsikrishna007

This comment has been minimized.

Copy link

vamsikrishna007 commented Feb 15, 2018

Neerajchhatani

Just include only column names and their values. If you are using any dropdown, then take the value of that which is stored in the Scope variable.

@royanon

This comment has been minimized.

Copy link

royanon commented Apr 9, 2018

This work in IE, Edge, FF and Chrome. Test on IE11.309.16299.0, Edge 41.16299.248.0, FF 59.2.3, Chrome 65.0.3325.181. Hope this help.
But it doesn't work in chrome when the file exceed 2Mb. It's very easy to hit 2Mb when the html consists of a lot of html.

// factory MyApp.factory('Excel', ["$window", function ($window) { var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>', base64 = function (s) { return $window.btoa(unescape(encodeURIComponent(s))); }, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }; return { tableToExcel: function (tableId, worksheetName, isBase64) { var table = document.querySelector(tableId); var ctx = { worksheet: worksheetName, table: table.innerHTML }; var href = ""; if (isBase64) { href = uri + base64(format(template, ctx)); } else { href = uri + format(template, ctx); } return href; } }; }]); // controller MyApp.controller('MyController', ["$scope", "$timeout", "Excel", function ($scope, $timeout, Excel) { $scope.exportToExcel = function (tableId) { var browser = window.navigator.appVersion; var useBlobBuilder = false; // IE, Edge if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) || (browser.indexOf('MSIE 10') !== -1) || (document.documentMode || /Edge/.test(browser))) { useBlobBuilder = true; $scope.exportHref = Excel.tableToExcel(tableId, 'sheet name', false); } else { //FF, Chrome useBlobBuilder = false; $scope.exportHref = Excel.tableToExcel(tableId, 'sheet name', true); } $timeout(function () { var fileName = "testing.xls"; if (useBlobBuilder) { // IE, Edge var builder = new window.MSBlobBuilder(); builder.append($scope.exportHref); var blob = builder.getBlob('data:application/vnd.ms-excel'); window.navigator.msSaveOrOpenBlob(blob, fileName); } else { //FF, Chrome var link = document.createElement('a'); link.download = fileName; link.href = $scope.exportHref; if (document.body != null) { document.body.appendChild(link); } link.click(); link.remove(); } }, 100); } }]);

@saravanajagan

This comment has been minimized.

Copy link

saravanajagan commented May 18, 2018

Working fine in Firefox. But not fully working in chrome... if the file size is more its redirecting to blank page.

Any solution?

@paunkumar

This comment has been minimized.

Copy link

paunkumar commented Jun 4, 2018

Working fine.
how to change as filename.

@muadib

This comment has been minimized.

Copy link

muadib commented Mar 30, 2019

if the code for download with a custom filename don't work in Firefox, change the else part in tableToExcel with:

var link = document.createElement('a');
link.setAttribute("type", "hidden"); // hide link
link.download = fileName;
link.href = uri + base64(format(template, ctx));
document.body.appendChild(link); //Required for Firefox
link.click();
link.remove();

And add in template, before </head>
<style><!-- table {mso-displayed-decimal-separator: "\.";mso-displayed-thousand-separator: "\,";} --></style>
For specify thousands separator and decimal separator.

@sri15941

This comment has been minimized.

Copy link

sri15941 commented Aug 12, 2019

i am getting only current page data downloaded. but i want all pages data to download.
what can i do.....?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.