Friday, April 22, 2011

ExtJS : Export DataGrid to Excel

I found an article in
http://loianegroner.com/2010/02/extjs-how-to-export-datagrid-to-excel/
but in the sencha forum, have this too
http://www.sencha.com/forum/showthread.php?32400-GridPanel-directly-to-Excel.
any way, this the article:
_____________________________________________________________________

This tutorial will walk through how to export data from ExtJS DataGrid directly to Excel.
Sometimes the user wants to export the data from the datagrid to an excel file. There is an ExtJS third party plugin that does it for you.
There are some “issues” you have to be aware of before you start:
  • It needs a browser that supports data URLs, such as Firefox, Opera and IE8.
  • I tested it with the following ExtJS versions: 2.2.1, 3.0, 3.0.3 and 3.1, but it only worked with ExtJS 3.0. If anyone is using other ExtJS version and the plugin worked, please, let me know.
  • It only works on the data in the Store – if you are using server-side paging, then perform this processing on the server. For quick and dirty conversion of a small table to Excel, this might be useful.
  • If the data in the Store is volatile (It gets reloaded or edited), the data URL will have to be recalculated.
Let’s get started:
First, create a file in your projet and paste this content in it (I called it exporter.js): http://github.com/loiane/extjs-export-excel/blob/master/WebContent/js/exporter.js (this file has too many lines, that’s why I’m not going to past its content here).
Then, in your datagrid, add this code:

var linkButton = new Ext.LinkButton({
id: 'grid-excel-button',
text: 'Export to Excel'
});
//create the Grid
var grid = new Ext.grid.GridPanel({
bbar: new Ext.Toolbar({
buttons: [linkButton]
})
});
linkButton.getEl().child('a', true).href = 'data:application/vnd.ms-excel;base64,' +
Base64.encode(grid.getExcelXml());
And if you try to export the data, it will look like this:

Feel free to change the color, fonts. Take a look in the code and try to understand it to make the changes you want.
Ed Spencer also developed a similar plugin. The source code is cleaner than this one. The output is the same, though.
You can download my sample app from my GitHub repository (JEE project): http://github.com/loiane/extjs-export-excel
Happy coding!
source : http://loianegroner.com/2010/02/extjs-how-to-export-datagrid-to-excel/

No comments:

Post a Comment