Extjs grid export to excel

I have a grid with large number of records. I use filters to filter the data as required. But i want to export the filtered data to a excel sheet for further usage.

I went through some articles available but they seem different and not compatible with latest 4.2 version.

Please help me in achieving this in simple manner.

Thanks much!

asked Jul 18, 2013 at 6:13

Anand Singh's user avatar

1

answered Nov 4, 2013 at 11:57

Argiropoulos Stavros's user avatar

2

As far as I know this isn’t possible without a Serverside implementation in a cross browser manner.

In theory you create a OpenXML document string by reading the current records from the store and encode it with base64. Then write this to a Data Uri. The first that didn’t allow inline data other then images is IE so this won’t work for all IE browser version due to limitations like size and images only. This will be the reason why there are no up to date implementations.

answered Jul 18, 2013 at 7:05

JJR's user avatar

JJRJJR

7731 gold badge13 silver badges32 bronze badges

2

Successfully implemented this approach for Ext JS 4. To give it a flexibility of an abstract class, follow the instructions:

  1. Take functions from here and extract them into a separate class
    as global.
  2. Replace all «this» function references to global function calls.

  3. Add «grid» parameter to all functions starting with the entry one
    (downloadExcelXml()).

  4. Replace the remaining «this» calls to grid references (as functions were expected to act inside a grid).

  5. Now add this button in your grid constructor and call
    downloadExcelXml() as a handler like this:

    exportButton = {
      xtype: 'button',
      text: 'xls',
      listeners: {
        click: function (button, event, eOpts) {
          downloadExcelXml(
            false,
            "TableHeader",
            eOpts.data.grid);
        },
      data: {
        grid: this
      }
    };
    

answered Apr 21, 2015 at 8:45

Zon's user avatar

ZonZon

17.9k6 gold badges88 silver badges95 bronze badges

1

Sometimes we want to print things, like grids or trees. The Ext JS printing plugin is pretty good for that. But what if we want to export them instead? Enter Ext.ux.Exporter.

Ext.ux.Exporter allows any store-based component (such as grids) to be exported, locally, to Excel or any other format. It does not require any server side programming – the export document is generated on the fly, entirely in JavaScript.

The extension serves as a base for exporting any kind of data, but comes bundled with a .xls export formatter suitable for exporting any Grid straight to Excel. Here’s how to do that:

var grid = new Ext.grid.GridPanel({
  store: someStore,
  tbar : [
    {
      xtype: 'exportbutton',
      store: someStore
    }
  ],
  //your normal grid config goes here
});

Clicking the Download button in the top toolbar iterates over the data in the store and creates an Excel file locally, before Base64 encoding it and redirecting the browser via a data url. If you have Excel or a similar program installed your browser should ask you to save the file or open it with Excel.

I put together a quick example of the plugin in action inside the repository, just clone or download the code and drag the examples/index.html file into your browser to run it.

The Exporter will work with any store or store-based component. It also allows export to any format – for example CSV or PDF. Although the Excel Formatter is probably the most useful, implementing a CSV or other Formatter should be trivial – check out the Excel Formatter example in the ExcelFormatter directory.

Содержание

  1. Extjs grid export to excel
  2. Intelligent Recommendation
  3. Vue export Excel in the front end
  4. Front end export table to Excel
  5. angular_1x front-end export excel
  6. Excel front-end import and export
  7. Excel export, front-end React
  8. More Recommendation
  9. Front-end excel export implementation
  10. Import Export of Front End Excel
  11. Front end Excel import and export
  12. How to export grid to XLS in ExtJS4.0
  13. 2 Answers 2
  14. How to export ExtJS GridPanel to Excel?
  15. 3 Answers 3
  16. Druck-I.T.
  17. I build great big things for the web.
  18. Generate an Excel File from an Ext JS 4 Grid or Store!
  19. Subhadip’s blog
  20. Thanks for coming.
  21. Exporting Excel and PDF files from EXTJS grid.
  22. Share this:
  23. Like this:
  24. One thought on “ Exporting Excel and PDF files from EXTJS grid. ”

Extjs grid export to excel

The js file supports the export of three-level headers.
Import the js file, call grid2Excel(grid, fileName).

  1. New export button
  1. Call this function after clicking.

List the detailed code:

Note:
The secondary and tertiary datagrid have merged cells. If there are serial numbers in the data list, they cannot be exported.
Solution:
1. Serial number column

The serial number column must be written like this

The dataIndex of the serial number column is operate. If this is included in the export function, it will not be exported (filtered).

However, writing in this way will be considered as a serial number, and a list with merged cells cannot be exported.

Intelligent Recommendation

Vue export Excel in the front end

I have also seen export order items before, but they have never been implemented. Recently, there is just a need to do this function! I also went to watch some blogs on the Internet, referenced.

Front end export table to Excel

html side On the js side, use blobs instead of base64 URLs when the amount of data is large. Tested 12M Excel data can support export.

angular_1x front-end export excel

1. Description: Today, a function to export excel should be done in the front end of angular. Find a relatively simple way is to export excel through alasql+xlsx. 2. The premise requires the introduct.

Excel front-end import and export

Pure front-end writing import, including style export excel-example is vue project Pure front end export excel (including style) 1. Install the plugin 2. If an error is reported, please modify the fol.

Excel export, front-end React

1. Install the plugin js-export-excel Two, code examples page first introduce the installed plugin Button transfer The name, deptName, and number are the data to be exported. What you want to export c.

More Recommendation

Front-end excel export implementation

Pure front end to realize Excel export data Scenario: Most of the time data export can directly request the back-end interface to complete the export, but sometimes the front-end needs to complete the.

Import Export of Front End Excel

Create-React-App Framework with ANTD and XLSX Implement Excel Import Export 1 Start yarn add xlsx 2 Excel import ImportExcelModel components Then use the components again The converted data is an arra.

Front end Excel import and export

Installation dependence Script xlsxKey The key corresponding to each column, the format is as follows.

Источник

How to export grid to XLS in ExtJS4.0

Is there a simple way to export a grid data to XLS in ExtJS.

If not I am trying the following way.

I am trying to read the data store inside a controller. The datastore is already being used by the grid. I want to read the data on a button click and send it to server through AJAX. Later inside server I would retrieve the data and write to XLS. In this case what is the way I can read the data inside the controller?

enter code here

2 Answers 2

I didn´t test it but it have to work. Good luck!

I think that process is not the best because you will have 3 payloads (data round trips that doesn’t make any sense)

Your call your server method to get the data that will be populated into the grid.

The JSON object (containing the server data) will then travel again to the server

(THIS DOESN’T MAKE SENSE TO ME. WHY YOU WANT TO SEND DATA TO SERVER WHEN THE SERVER WAS THE SOURCE?? )

What I think you should do is the following:

  1. Get data from server and bind your grid.
  2. Get your store proxy URL and parse the method and extraParams so you know who served the grid and what you asked to the server.
  3. Create a common method on server that receives a method and an array of parameters . Then inside this method make the logic so depending on the method, you call your data Repository (same repository where your first request got the data), process the document and send the file back to server.

This way you should have something like this:

Источник

How to export ExtJS GridPanel to Excel?

I want to export my GridPanel to Excel. I searched too many times but I couldn’t find any acceptable solution.

Can you help me about this problem?

P.S.: I use ExtJS 3.2 and 3.3.1

3 Answers 3

There isn’t any good solution to generate xls/xlsx in javascript.

Your best catch is to do it server-side.

Send ajax request to http://your-website.com/generate_xls containing all the data, and return xls headers and then body.

Here is a good PHP library, in case that you are using PHP: http://phpexcel.codeplex.com/

This is a server side job. Here is what I use for generating tabular reports which are based on Grid data: http://xmlgraphics.apache.org/fop/

Also, you can generate a very nice, fully functional Excel spreadsheet from tabular data: http://msdn2.microsoft.com/en-us/lib. ffice.10).aspx

.With the launch of ExtJS 5, it’s probably better to start porting your application to a newer version of ExtJS, at least 4.

We have created a front-end XLS(X) and CSV import and export tool that you can use in ExtJS 4 applications with a few lines of code. The user just drags the file on the grid and done. We just launched it, here is a description: http://2gears.com/2014/08/ext-js-excel-import-export-easy/

As said, the import and export is done ENTIRELY client side, so in applications with many concurrent users, this relieves the server from excessive load. In the next weeks also an import wizard will be added, that guides less capable users in importing files.

Источник

Druck-I.T.

I build great big things for the web.

Generate an Excel File from an Ext JS 4 Grid or Store!

(updated on March 19, 2014 to support grouped grids)
(updated on April 3, 2014 to support Microsoft Internet Explorer)
(updated on Nov 16, 2014 to fix various issues with grouping)

Recently I was tasked with building an application whereby the user could export report data contained within a grid to Microsoft Excel. Under normal circumstances, I would have used a server-side approach using ColdFusion’s robust functionality. However, in this particular case, we were using .NET and frankly, I wanted the middleware developer on the project to stay focused on building the core .NET CRUD webservices that were required for the project.

Much to my surprise, after spending a good amount of time googling for a solution, there didn’t seem to be a really dead-simple implementation of a Grid to Excel method for Ext JS 4.

There were several Ext 3 examples available, however. So I ported and enhanced one that I found out there for your enjoyment.

Here’s the result, which I implemented as an override to the grid control. Calling it’s rather quite simple. Just invoke the grid’s downloadExcelXml() method.

Converting over the Ext 3 code and enhancing it to supply a suggested filename using a new Google Chrome trick, wasn’t quite so simple:

The server-side code used to echo the generated spreadsheet back to the browser and force a “download” operation is the following:

Note that the ColdFusion-based “echo” webservice is available for evaluation/testing purposes only. No warranty or level of service is expressed or implied.

Источник

Subhadip’s blog

Thanks for coming.

Exporting Excel and PDF files from EXTJS grid.

Sencha EXTJS as you know is a Rich Javascript platform which supports amazing functionalities with ease. It’s really fun to work on this technology.

But one of the most challenging functionality I have faced is to provide a UI soln. for exporting Excel and PDF files on the go from EXTJS grid on the client side using Javascript only. Well I know some of you might be aware of this feature but this post might be helpful for many.

Well to begin this tutorial will include simplest ways of achieving the desired output (i.e. generation of Excel and a PDF file.)

A> Generation of Excel file from the grid.

I will assume you have already configured your EXTJS project and everything is working fine.

For genaration of excel from EXTJS grid we would be using —- Ext.ux.exporter with adobe Downloadify for downloading the file .

  1. Download my version of Exporter from SourceForge->https://sourceforge.net/projects/extjsexcelexport/ > Files
  2. Once you download it, unpack the entire contents in “/extjs/ux” folder.
  3. If you have a parent JSP file or HTML file where you already have included the ext-all-debug.js, include the following entries.
  4. Now, if you have a parent JS file like Application.js include the following lines at the top Ext.Loader.setConfig(<enabled : true>);
    Ext.Loader.setPath(‘Ext.ux’, ‘extjs/ux’);
  5. Once that is done, you can directly use the Exporter button widget in the docked items of the Grid. <
    xtype: ‘pagingtoolbar’,
    store: ‘MyProject.CountryStore’,
    margin:’0 0 0 10′,
    id :’countryPaging’,
    cls :’paginationToolbar’,
    items: [
    <
    xtype: ‘exporterbutton’
    >]
    >

We are done…Please modify the Worksheet.js file which I have customized as per my project requirements, where in we had to include the search criteria. If you dont need that you can eliminate the buildSearchParams, method. Instead write your own logic here.

B> Generation of PDF file from the grid.

We will be using JSPDF for this. JSPDF is a third party tool, which is developed by parallax software labs. Though it is stable I could not get it to working for generation of PDF from HTML. It is still in development phase.

JSPDF works with JQuery, EXTJs and Jqeuery usage simultaneously is not recommended in my project.

The only feature of JSPDF that works for me, is normal text generation and drawing lines.

What I did is I converted the Grid data into Arrays, i.e. gridData = [<[cell1],[cell2]…>, <[cell1],[cell2].. >, … ] likewise.

Now, iterate the array and manually position the elements into PDF.

var doc = new jsPDF(‘p’, ‘pt’, ‘a1’, true);

Ext.each(data, function(row, i)<
if(countRow%(maxRowsOnPage) == 0 && i != 0 )<

//adding a new pager after max no. of rows on page

doc.addPage();
pageNo ++;
countRow = 0;
doc.setDrawColor(0,0,0);
doc.line(35, 125, 250*(cols), 125);
>
Ext.each(row, function(cell, j)<
doc.text(45+(j*200), 145+(countRow*30), cell ) ;

//vertical lines
doc.line(35+(j*200), 125+(countRow*30), 35+(j*200), 155+(countRow*30) );

//Last vertical lines
doc.line(50+((cols+1)*200), 125+(countRow*30), 50+((cols+1)*200), 155+(countRow*30) );
//row horizontal lines
doc.line(35, 155+(countRow*30), 250*cols , 155+(countRow*30));
>);

doc.save(‘GridExport.pdf’);

You can put this piece of code inside the listener handler : function() <> of the PDF icon in your paging toolbar.

One more thing for this to work, download jsPDF from gitHub –> https://github.com/MrRio/jsPDF and only include these two files in your parent JSP, thats it.

Hope this solves your problems…keep posting your comments and let me know if this post is of any use to you.

For any queries please write to me on subhadip0608@gmail.com

Like this:

One thought on “ Exporting Excel and PDF files from EXTJS grid. ”

function _getFieldText(fieldData) <
var text;
if(fieldData == ‘‘ ||
fieldData == ‘‘ ||
fieldData == ‘‘ ||
fieldData == ‘‘) <
text = ‘u2714’
>
if (fieldData == null || fieldData == undefined) <
text = »;

> else if (fieldData instanceof Date) <
text = Ext.Date.format(fieldData, this.dateFormat);

> else if (!fieldData.match) < // not a string or object we
// recognize. bank it out
text = »;

> else <
text = fieldData;
>

function getCSV(grid) <
var cols = grid.columns;
var store = grid.store.snapshot;
var data = [];
var textData = [];
var columns = [];
var CSV = »;
var colData = »;
//var ReportTitle = «Report»;
// CSV += ReportTitle + ‘rnn’;
var that = this;
Ext.Array.each(cols, function(col, index) <
if (col.hidden != true) <
columns.push(that._getFieldTextAndEscape(col.text));
>
>);
textData.push(columns);
store.each(function(record) <
var entry = record.getData();
var data = [];
Ext.Array.each(cols, function(col, index) <
if (col.hidden != true) <
var fieldName = col.dataIndex;
var text = entry[fieldName];
if(fieldName == ‘dfltSecLdgrAccnTyp’ && text==true) <
text = ‘Y’;
>
if(fieldName == ‘dfltSecClntAccTyp’ && text==true) <
text = ‘Y’;
>
if(fieldName == ‘dfltCshLdgrAccnTyp’ && text==true) <
text = ‘Y’;
>
if(fieldName == ‘dfltCshClntAccTyp’ && text==true) <
text = ‘Y’;
>
data.push(that._getFieldTextAndEscape(text));
>
>);
textData.push(data);
>);

function _getFieldTextAndEscape(fieldData) <
var string = this._getFieldText(fieldData);

return this._escapeForCSV(string);
>
function _ieGetGridData(grid, sheet) <
var that = this;
var resourceItems = grid.store.data.items;
var cols = grid.columns;

Ext.Array.each(cols, function(col, colIndex) <
if (col.hidden != true) <
//console.log(‘header: ‘, col.text);
sheet.cells(1, colIndex + 1).value = col.text;
>
>);

var rowIndex = 2;
grid.store.each(function(record) <
var entry = record.getData();

Ext.Array.each(cols, function(col, colIndex) <
if (col.hidden != true) <
var fieldName = col.dataIndex;
var text = entry[fieldName];
var value = that._getFieldText(text);

sheet.cells(rowIndex, colIndex + 1).value = value;
>
>);
rowIndex++;
>);
>

function _escapeForCSV(string) <
if (string.match(/,/)) <
if (!string.match(/»/)) <
string = ‘»‘ + string + ‘»‘;
> else <
string = string.replace(/,/g, »); // comma’s and quotes— sorry,
// just loose the commas
>
>
return string;
>

function _ieToExcel(grid) <
//console.log(window.ActiveXObject);
if (window.ActiveXObject) <
var xlApp, xlBook;
try <
xlApp = new ActiveXObject(«Excel.Application»);
xlBook = xlApp.Workbooks.Add();
> catch (e) <
Ext.Msg
.alert(
‘Error’,
‘For the export to work in IE, you have to enable a security setting called «Initialize and script ActiveX control not marked as safe» from Internet Options -> Security -> Custom level. «‘);
return;
>

xlBook.worksheets(«Sheet1»).activate;
var XlSheet = xlBook.activeSheet;
xlApp.visible = true;

this._ieGetGridData(grid, XlSheet);
XlSheet.columns.autofit;
>
>
function convertParamForPresentation(param) <
var paramMap = param.split(«:»);
var paramKey = getSearchKey(paramMap[0]);
var value = paramMap[1];
if (NWMRuntimeVariables.currentGridId == ‘providersGrid’) <
if (value == ‘A’) <
value = ‘Active’;
> else if (value == ‘I’) <
value = ‘Inactive’;
> else if (value == ‘D’) <
value = ‘Discard’;
>
> else if (NWMRuntimeVariables.currentGridId == ‘accountGrid’) <
if (value == ‘A’) <
value = ‘Active’;
> else if (value == ‘I’) <
value = ‘Inactive’;
> else if (value == ‘D’) <
value = ‘Dormant’;
> else if (value == ‘O’) <
value = ‘Others’;
>

else if (value == ‘CE’) <
value = ‘Cash External’;
> else if (value == ‘CL’) <
value = ‘Cash Ledger’;
>
>
var excelSearchCiteria = paramKey + ‘ : ‘ + value;
return excelSearchCiteria;
>

Источник

(updated on March 19, 2014 to support grouped grids)
(updated on April 3, 2014 to support Microsoft Internet Explorer)
(updated on Nov 16, 2014 to fix various issues with grouping)

Recently I was tasked with building an application whereby the user could export report data contained within a grid to Microsoft Excel. Under normal circumstances, I would have used a server-side approach using ColdFusion’s robust functionality. However, in this particular case, we were using .NET and frankly, I wanted the middleware developer on the project to stay focused on building the core .NET CRUD webservices that were required for the project.

Image

Much to my surprise, after spending a good amount of time googling for a solution, there didn’t seem to be a really dead-simple implementation of a Grid to Excel method for Ext JS 4.

There were several Ext 3 examples available, however. So I ported and enhanced one that I found out there for your enjoyment.

Here’s the result, which I implemented as an override to the grid control. Calling it’s rather quite simple. Just invoke the grid’s downloadExcelXml() method.

 {
   xtype: 'button',
   flex: 1,
   text: 'Download to Excel',
   handler: function(b, e) {
     b.up('grid').downloadExcelXml();
   }
 }

Converting over the Ext 3 code and enhancing it to supply a suggested filename using a new Google Chrome trick, wasn’t quite so simple:

Ext.define('MyApp.view.override.Grid', {
    override: 'Ext.grid.GridPanel',
    requires: 'Ext.form.action.StandardSubmit',

    /*
        Kick off process
    */

    downloadExcelXml: function(includeHidden, title) {

        if (!title) title = this.title;

        var vExportContent = this.getExcelXml(includeHidden, title);

        var location = 'data:application/vnd.ms-excel;base64,' + Base64.encode(vExportContent);

        /* 
          dynamically create and anchor tag to force download with suggested filename 
          note: download attribute is Google Chrome specific
        */

        if (!Ext.isChrome) {
            var gridEl = this.getEl();

            var el = Ext.DomHelper.append(gridEl, {
                tag: "a",
                download: title + "-" + Ext.Date.format(new Date(), 'Y-m-d Hi') + '.xls',
                href: location
            });

            el.click();

            Ext.fly(el).destroy();

        } else {

            var form = this.down('form#uploadForm');
            if (form) {
                form.destroy();
            }
            form = this.add({
                xtype: 'form',
                itemId: 'uploadForm',
                hidden: true,
                standardSubmit: true,
                url: 'http://webapps.figleaf.com/dataservices/Excel.cfc?method=echo&mimetype=application/vnd.ms-excel&filename=' + escape(title + ".xls"),
                items: [{
                    xtype: 'hiddenfield',
                    name: 'data',
                    value: vExportContent
                }]
            });

            form.getForm().submit();

        }
    },

    /*

        Welcome to XML Hell
        See: http://msdn.microsoft.com/en-us/library/office/aa140066(v=office.10).aspx
        for more details

    */
    getExcelXml: function(includeHidden, title) {

        var theTitle = title || this.title;

        var worksheet = this.createWorksheet(includeHidden, theTitle);
        var totalWidth = this.columnManager.columns.length;

        return ''.concat(
            '<?xml version="1.0"?>',
            '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">',
            '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Title>' + theTitle + '</Title></DocumentProperties>',
            '<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"><AllowPNG/></OfficeDocumentSettings>',
            '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">',
            '<WindowHeight>' + worksheet.height + '</WindowHeight>',
            '<WindowWidth>' + worksheet.width + '</WindowWidth>',
            '<ProtectStructure>False</ProtectStructure>',
            '<ProtectWindows>False</ProtectWindows>',
            '</ExcelWorkbook>',

            '<Styles>',

            '<Style ss:ID="Default" ss:Name="Normal">',
            '<Alignment ss:Vertical="Bottom"/>',
            '<Borders/>',
            '<Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="12" ss:Color="#000000"/>',
            '<Interior/>',
            '<NumberFormat/>',
            '<Protection/>',
            '</Style>',

            '<Style ss:ID="title">',
            '<Borders />',
            '<Font ss:Bold="1" ss:Size="18" />',
            '<Alignment ss:Horizontal="Center" ss:Vertical="Center" ss:WrapText="1" />',
            '<NumberFormat ss:Format="@" />',
            '</Style>',

            '<Style ss:ID="headercell">',
            '<Font ss:Bold="1" ss:Size="10" />',
            '<Alignment ss:Horizontal="Center" ss:WrapText="1" />',
            '<Interior ss:Color="#A3C9F1" ss:Pattern="Solid" />',
            '</Style>',


            '<Style ss:ID="even">',
            '<Interior ss:Color="#CCFFFF" ss:Pattern="Solid" />',
            '</Style>',


            '<Style ss:ID="evendate" ss:Parent="even">',
            '<NumberFormat ss:Format="yyyy-mm-dd" />',
            '</Style>',


            '<Style ss:ID="evenint" ss:Parent="even">',
            '<Numberformat ss:Format="0" />',
            '</Style>',

            '<Style ss:ID="evenfloat" ss:Parent="even">',
            '<Numberformat ss:Format="0.00" />',
            '</Style>',

            '<Style ss:ID="odd">',
            '<Interior ss:Color="#CCCCFF" ss:Pattern="Solid" />',
            '</Style>',

            '<Style ss:ID="groupSeparator">',
            '<Interior ss:Color="#D3D3D3" ss:Pattern="Solid" />',
            '</Style>',

            '<Style ss:ID="odddate" ss:Parent="odd">',
            '<NumberFormat ss:Format="yyyy-mm-dd" />',
            '</Style>',

            '<Style ss:ID="oddint" ss:Parent="odd">',
            '<NumberFormat Format="0" />',
            '</Style>',

            '<Style ss:ID="oddfloat" ss:Parent="odd">',
            '<NumberFormat Format="0.00" />',
            '</Style>',


            '</Styles>',
            worksheet.xml,
            '</Workbook>'
        );
    },

    /*

        Support function to return field info from store based on fieldname

    */

    getModelField: function(fieldName) {

        var fields = this.store.model.getFields();
        for (var i = 0; i < fields.length; i++) {
            if (fields[i].name === fieldName) {
                return fields[i];
            }
        }
    },

    /*
        
        Convert store into Excel Worksheet

    */
    generateEmptyGroupRow: function(dataIndex, value, cellTypes, includeHidden) {


        var cm = this.columnManager.columns;
        var colCount = cm.length;
        var rowTpl = '<Row ss:AutoFitHeight="0"><Cell ss:StyleID="groupSeparator" ss:MergeAcross="{0}"><Data ss:Type="String"><html:b>{1}</html:b></Data></Cell></Row>';
        var visibleCols = 0;

        // rowXml += '<Cell ss:StyleID="groupSeparator">'

        for (var j = 0; j < colCount; j++) {
            if (cm[j].xtype != 'actioncolumn' && (cm[j].dataIndex != '') && (includeHidden || !cm[j].hidden)) {
                // rowXml += '<Cell ss:StyleID="groupSeparator"/>';
                visibleCols++;
            }
        }

        // rowXml += "</Row>";

        return Ext.String.format(rowTpl, visibleCols - 1, value);
    },


    createWorksheet: function(includeHidden, theTitle) {
        // Calculate cell data types and extra class names which affect formatting
        var cellType = [];
        var cellTypeClass = [];
        var cm = this.columnManager.columns;

        var totalWidthInPixels = 0;
        var colXml = '';
        var headerXml = '';
        var visibleColumnCountReduction = 0;
        var colCount = cm.length;
        for (var i = 0; i < colCount; i++) {
            if (cm[i].xtype != 'actioncolumn' && (cm[i].dataIndex != '') && (includeHidden || !cm[i].hidden)) {
                var w = cm[i].getEl().getWidth();
                totalWidthInPixels += w;

                if (cm[i].text === "") {
                    cellType.push("None");
                    cellTypeClass.push("");
                    ++visibleColumnCountReduction;
                } else {
                    colXml += '<Column ss:AutoFitWidth="1" ss:Width="' + w + '" />';
                    headerXml += '<Cell ss:StyleID="headercell">' +
                        '<Data ss:Type="String">' + cm[i].text + '</Data>' +
                        '<NamedCell ss:Name="Print_Titles"></NamedCell></Cell>';


                    var fld = this.getModelField(cm[i].dataIndex);
                    switch (fld.type.type) {
                        case "int":
                            cellType.push("Number");
                            cellTypeClass.push("int");
                            break;
                        case "float":
                            cellType.push("Number");
                            cellTypeClass.push("float");
                            break;

                        case "bool":

                        case "boolean":
                            cellType.push("String");
                            cellTypeClass.push("");
                            break;
                        case "date":
                            cellType.push("DateTime");
                            cellTypeClass.push("date");
                            break;
                        default:
                            cellType.push("String");
                            cellTypeClass.push("");
                            break;
                    }
                }
            }
        }
        var visibleColumnCount = cellType.length - visibleColumnCountReduction;

        var result = {
            height: 9000,
            width: Math.floor(totalWidthInPixels * 30) + 50
        };

        // Generate worksheet header details.

        // determine number of rows
        var numGridRows = this.store.getCount() + 2;
        if (!Ext.isEmpty(this.store.groupField) || this.store.groupers.items.length > 0) {
            numGridRows = numGridRows + this.store.getGroups().length;
        }

        // create header for worksheet
        var t = ''.concat(
            '<Worksheet ss:Name="' + theTitle + '">',

            '<Names>',
            '<NamedRange ss:Name="Print_Titles" ss:RefersTo="='' + theTitle + ''!R1:R2">',
            '</NamedRange></Names>',

            '<Table ss:ExpandedColumnCount="' + (visibleColumnCount + 2),
            '" ss:ExpandedRowCount="' + numGridRows + '" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="65" ss:DefaultRowHeight="15">',
            colXml,
            '<Row ss:Height="38">',
            '<Cell ss:MergeAcross="' + (visibleColumnCount - 1) + '" ss:StyleID="title">',
            '<Data ss:Type="String" xmlns:html="http://www.w3.org/TR/REC-html40">',
            '<html:b>' + theTitle + '</html:b></Data><NamedCell ss:Name="Print_Titles">',
            '</NamedCell></Cell>',
            '</Row>',
            '<Row ss:AutoFitHeight="1">',
            headerXml +
            '</Row>'
        );

        // Generate the data rows from the data in the Store
        var groupVal = "";
        var groupField = "";
        if (this.store.groupers.keys.length > 0) {
            groupField = this.store.groupers.keys[0];
        }
        for (var i = 0, it = this.store.data.items, l = it.length; i < l; i++) {

            if (!Ext.isEmpty(groupField)) {
                if (groupVal != this.store.getAt(i).get(groupField)) {
                    groupVal = this.store.getAt(i).get(groupField);
                    t += this.generateEmptyGroupRow(groupField, groupVal, cellType, includeHidden);
                }
            }
            t += '<Row>';
            var cellClass = (i & 1) ? 'odd' : 'even';
            r = it[i].data;
            var k = 0;
            for (var j = 0; j < colCount; j++) {
                if (cm[j].xtype != 'actioncolumn' && (cm[j].dataIndex != '') && (includeHidden || !cm[j].hidden)) {
                    var v = r[cm[j].dataIndex];
                    if (cellType[k] !== "None") {
                        t += '<Cell ss:StyleID="' + cellClass + cellTypeClass[k] + '"><Data ss:Type="' + cellType[k] + '">';
                        if (cellType[k] == 'DateTime') {
                            t += Ext.Date.format(v, 'Y-m-d');
                        } else {
                            t += v;
                        }
                        t += '</Data></Cell>';
                    }
                    k++;
                }
            }
            t += '</Row>';
        }

        result.xml = t.concat(
            '</Table>',
            '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">',
            '<PageLayoutZoom>0</PageLayoutZoom>',
            '<Selected/>',
            '<Panes>',
            '<Pane>',
            '<Number>3</Number>',
            '<ActiveRow>2</ActiveRow>',
            '</Pane>',
            '</Panes>',
            '<ProtectObjects>False</ProtectObjects>',
            '<ProtectScenarios>False</ProtectScenarios>',
            '</WorksheetOptions>',
            '</Worksheet>'
        );
        return result;
    }
});

The server-side code used to echo the generated spreadsheet back to the browser and force a “download” operation is the following:

<cfcomponent>

 <cffunction name="echo" access="remote" returntype="void">

 <cfargument name="mimetype" type="string" required="no" default="text/html">
 <cfargument name="filename" type="string" required="yes">
 <cfargument name="data" type="string" required="no" default="">

 <cfif isdefined("form.data")>
 <cfset arguments.data = form.data>
 </cfif>

 <cfheader name="Content-Disposition" value="attachment; filename=#arguments.filename#">

 <cfcontent type="#arguments.mimetype#"><cfoutput>#arguments.data#</cfoutput>

 </cffunction>

</cfcomponent>

Note that the ColdFusion-based “echo” webservice is available for evaluation/testing purposes only. No warranty or level of service is expressed or implied.

You can play around with the code on Sencha Fiddle:
https://fiddle.sencha.com/#fiddle/17j

Go check it out!

The js file supports the export of three-level headers.
Import the js file, call grid2Excel(grid, fileName).

  1. New export button
new Ext.create('Ext.button.Button',{ 
    xtype:'button', 
    iconCls:'excel', 
    type: 'excel', 
    text:'Save as Excel', 
    handler:function() { 
         //grid is the Extjs grid object 
         //"Export file name" is the name of the exported Excel file                     
        grid2Excel(grid,"Project Authorization List"); 
    } 
})
  1. Call this function after clicking.

List the detailed code:

/** 
* 
* function grid2Excel(grid,filename) 
* @param grid Extjs grid panel 
* @param  filename Excel file name 
* 
* **/ 
(function(){ 
            function  getExplorer() {
            var explorer = window.navigator.userAgent ;
            //ie 
            if (explorer.indexOf("MSIE") >= 0) {
                return 'ie';
            }
            //firefox 
            else if (explorer.indexOf("Firefox") >= 0) {
                return 'Firefox';
            }
            //Chrome
            else if(explorer.indexOf("Chrome") >= 0){
                return 'Chrome';
            }
            //Opera
            else if(explorer.indexOf("Opera") >= 0){
                return 'Opera';
            }
            //Safari
            else if(explorer.indexOf("Safari") >= 0){
                return 'Safari';
            }         
        }

         function export_excel_ie(tableStr, fileName) {//Copy the entire table to EXCEL
            if(getExplorer()=='ie')
            {
                var oXL = new ActiveXObject("Excel.Application");
                /*
                                   * Set the border, 1 means the thinnest border, 2 means thin border, 4 means thick line.
                 */
                //oXL.Selection.Borders.Weight = 4;
                /*
                                   * Set the border line 1 solid line, -4115 dotted line, 4 dotted line, 5 dotted line followed by two dots, -4118 dotted line, -4119 double line.
                 */
                //oXL.Selection.Borders.LineStyle = 1;
                var el4table = document.createElement("div");
                el4table.innerHTML = tableStr;
                //Create AX object excel 
                var oWB = oXL.Workbooks.Add();
                //Get workbook object 
                var xlsheet = oWB.Worksheets(1);
                //Activate the current sheet 
                var sel = document.body.createTextRange();
                sel.moveToElementText(el4table);
                //Move the contents of the table to TextRange 
                sel.select;
                //Select all content in TextRange 
                sel.execCommand("Copy");
                //Copy the content in TextRange  
                xlsheet.Paste();
                //Paste into the activity's EXCEL       
                oXL.Visible = true;
                //Set the visible attributes of excel

                try {
                    var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
                } catch (e) {
                    print("Nested catch caught " + e);
                } finally {
                    oWB.SaveAs(fname);

                    oWB.Close(savechanges = false);
                    //xls.visible = false;
                    oXL.Quit();
                    oXL = null;
                    //End the excel process, exit is complete
                    //window.setInterval("Cleanup();",1);
                    idTmr = window.setInterval("Cleanup();", 1);

                }

            }
            else
            {
                tableToExcel(tableStr, fileName);
            }
        }
        function Cleanup() {
            window.clearInterval(idTmr);
            CollectGarbage();
        }
    var Base64 = (function() { 
        // private property 
        var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 

        // private method for UTF-8 encoding 
        function utf8Encode(string) { 
            string = string.replace(/rn/g,"n"); 
            var utftext = ""; 
            for (var n = 0; n < string.length; n++) { 
                var c = string.charCodeAt(n); 
                if (c < 128) { 
                    utftext += String.fromCharCode(c); 
                } 
                else if((c > 127) && (c < 2048)) { 
                    utftext += String.fromCharCode((c >> 6) | 192); 
                    utftext += String.fromCharCode((c & 63) | 128); 
                } 
                else { 
                    utftext += String.fromCharCode((c >> 12) | 224); 
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128); 
                    utftext += String.fromCharCode((c & 63) | 128); 
                } 
            } 
            return utftext; 
        } 

        // public method for encoding 
        return { 
            //encode : (typeof btoa == 'function') ? function(input) { return btoa(input); } : function (input) { 
            encode : function (input) { 
                var output = ""; 
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4; 
                var i = 0; 
                input = utf8Encode(input); 
                while (i < input.length) { 
                    chr1 = input.charCodeAt(i++); 
                    chr2 = input.charCodeAt(i++); 
                    chr3 = input.charCodeAt(i++); 
                    enc1 = chr1 >> 2; 
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 
                    enc4 = chr3 & 63; 
                    if (isNaN(chr2)) { 
                        enc3 = enc4 = 64; 
                    } else if (isNaN(chr3)) { 
                        enc4 = 64; 
                    } 
                    output = output + 
                        keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
                        keyStr.charAt(enc3) + keyStr.charAt(enc4); 
                } 
                return output; 
            } 
        }; 
    })(); 
    var  format = function(s, c) { return s.replace(/{(w+)}/g, function(m, p) { return c[p]; }) }; 
    var tableToExcel = function(table, fileName) { 
        var uri = 'data:application/vnd.ms-excel;base64,' 
            ,fileName = fileName || 'excelexport' 
        , 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 name="renderer" content="webkit"><!--[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 ctx = {worksheet:'Worksheet', table: table}; 
        var a = document.createElement('a'); 
        document.body.appendChild(a); 
        a.hreflang = 'zh'; 
        a.charset = 'utf8'; 
        a.type="application/vnd.ms-excel"; 
        a.href = uri + Base64.encode(format(template,ctx)); 
        a.target = '_blank'; 
        a.download = fileName + '.xls';
        a.tableBorder = 1;
        a.click(); 

    }; 
    window.grid2Excel = function(grid, fileName) { 
//      console.log(grid);
        var columns = grid.initialConfig.columns|| [], 
            store = grid.getStore(), 
            headLevel1 = [],headLevel2 = [], headLevel3 = [], headLevel = 1,isGroup = false, isGroup3 = false,
            dataIndex =[],tableStr = '<table border="1" bordercolor="#000"><thead>{thead}</thead><tbody>{tbody}</tbody></table>'; 

        var blankColumn = 0;
        var blankColumn3 = 0;
        var ifWithCheckOrNumFirst;
        columns.forEach(function(column) {

                //Description that the first column is a checkbox or a serial number column, it has a headerId, if not a headerId
            //console.log(!column.headerId);
                if(column.headerId){
// console.log("Sequence number column");
                    ifWithCheckOrNumFirst = true;
                } else {
                    //With merged cells, there is no dataindex in that one column, so it will be false
                    if(!column.dataIndex) {

                        blankColumn += 1;
                        isGroup = true; 

                        var items = column.columns ||[];
                        items.forEach(function(column3) {
                            if (!column3.dataIndex) {
                                blankColumn3 += 1;  //Divided into the number of three-level headers
                                isGroup3 = true;    //Three-level header
                                return false;
                            }
                        });                     
                        return false; 
                    } 
                }
        }); 
        if(isGroup) { 
            headLevel = 2;  //Only supports secondary header 
            if (isGroup3) {
                headLevel = 3;
            }
        } 
// console.log("------------Header: "+ headLevel);
// console.log("Three-level header: "+ blankColumn3);

        var indexen = 0;
     // console.log("length1:" + headLevel1.length);
        columns.forEach(function(column) { 
            //    console.log(column.dataIndex);

                //When you do not need to merge cells horizontally,
            if(column.dataIndex) { 
          //    console.log(column);
                column.colspan = 1;

                //If there are horizontal merged cells, this vertical merge will increase. If it’s a 2-layer header, the rowspan is 2. In fact, it doesn’t matter whether he merges horizontally or not, it’s right
                if (headLevel == 3) {
                    column.rowspan = headLevel; 
                } else if (headLevel == 2) {
                    column.rowspan = headLevel; 
                } else {
                    column.rowspan = 1;
                }               

                headLevel1.push(column); 
                dataIndex.push(column); 

            }else { 
          // console.log("lengthx333:" + headLevel); 
                //It is not a horizontally merged cell, and it may be that the first column is a checkbox or a serial number, so you need to judge, if it is a checkbox or a serial number, it is not pushed into the array
                if (ifWithCheckOrNumFirst) {

                } else {
                    var items = column.columns ||[]; 
                    headLevel1.push(column);
                    items.forEach(function(item2) {
                    // console.log("secondary dataindex: "+ item2.dataIndex);
                        if (item2.dataIndex) {//Secondary header 
                            column.colspan = items.length;
                            column.rowspan = 1;
                            item2.colspan = 1;
                            if (headLevel == 3) {//Under the third-level header If there is no further division under the second-level header, the second-level header will occupy two rows
                                item2.rowspan = 2;
                            } else {
                                item2.rowspan = 1;
                            }

                            headLevel2.push(item2);
                            dataIndex.push(item2);
                        } else {
                            var items3 = item2.columns ||[];
                            headLevel2.push(item2);
                            items3.forEach(function(item33) {
                                if (item33.dataIndex) {
                                    item2.colspan = items3.length;//The length of the secondary header
                                    column.colspan = items3.length + items.length + blankColumn3; //The length of the first level header
                                    item2.rowspan = 1;
                                    item33.colspan = 1;
                                    item33.rowspan = 1;
                                    headLevel3.push(item33);
                                    dataIndex.push(item33);
                                }

                            });
                        }

                    });
                }
            } 
        }); 

        var headLevel1Str = '<tr>'; 
        headLevel1.forEach(function(head) { 
       //   console.log(head.header);
            if (head.dataIndex != 'operate') {
                headLevel1Str += '<th colspan = "'+head.colspan+ 
                    '" rowspan="'+head.rowspan+'">'+head.header+'</th>'; 
            }

        }); 
        headLevel1Str += '</tr>'; 

        var headLevel2Str = ''; 
        if(headLevel2.length > 0) { 
            headLevel2Str += '<tr>'; 
            headLevel2.forEach(function(head) { 
                if (head.dataIndex != 'operate') {
                    headLevel2Str += '<th colspan = "'+head.colspan+ 
                        '" rowspan="'+head.rowspan+'">'+head.header+'</th>'; 
                }
            }); 
            headLevel2Str += '</tr>' 
        } 

        var headLevel3Str = ''; 
        if(headLevel3.length > 0) { 
            headLevel3Str += '<tr>'; 
            headLevel3.forEach(function(head) { 
                if (head.dataIndex != 'operate') {
                    headLevel3Str += '<th colspan = "'+head.colspan+ 
                        '" rowspan="'+head.rowspan+'">'+head.header+'</th>'; 
                }
            }); 
            headLevel3Str += '</tr>' 
        } 

        var theadStr = headLevel1Str + headLevel2Str + headLevel3Str, 
            tbodyStr = '',defRenderer = function(value) { 
                return value; 
            }; 

        store.each(function(r) { 
            tbodyStr += '<tr>'; 
            dataIndex.forEach(function(c) { 
                if (c.dataIndex != 'operate') {
                    var renderere = c.renderer || defRenderer; 
                    if (renderere.call(r,r.get(c.dataIndex))) {
                        tbodyStr += '<td>'+renderere.call(r,r.get(c.dataIndex)) + "" +'</td>' ;
                    } else {
                        tbodyStr += '<td>'+ " " + "" +'</td>' ;
                    }
                    tbodyStr += '<td>'+renderere.call(r,r.get(c.dataIndex)) + "" +'</td>' ;
                //  console.log("test: " + renderere.call(r,r.get(c.dataIndex)));
                }

            }); 
            tbodyStr +='</tr>' 
        }); 
        tableStr = format(tableStr,{ 
            thead:theadStr, 
            tbody:tbodyStr 
        }); 

     //   console.log(tableStr);
        export_excel_ie(tableStr,fileName); 

    } 
})()

Note:
The secondary and tertiary datagrid have merged cells. If there are serial numbers in the data list, they cannot be exported.
Solution:
1. Serial number column

The serial number column must be written like this

{ header: '', xtype: 'rownumberer',dataIndex:'operate', width: 60, align: 'center', sortable: false },

The dataIndex of the serial number column is operate. If this is included in the export function, it will not be exported (filtered).

However, writing in this way will be considered as a serial number, and a list with merged cells cannot be exported.

new Ext.grid.RowNumberer({  header: 'Serial number',   width:50}),
  • Checkbox column
checkBox = Ext.create('Ext.selection.CheckboxModel', {
    mode : "SIMPLE",
    checkOnly : true
});
grid = Ext.create('Ext.grid.GridPanel', {
    renderTo : 'gridDiv',
    title : 'Personnel assessment list',
    sripeRows : true,
    store : store,
    // bodyStyle: 'width:100%',
    viewConfig : {
        forceFit : true
    },
         selModel: checkBox,//Set check box
}

Понравилась статья? Поделить с друзьями:
  • External data sources excel
  • Extensive meaning of the word
  • Extension for microsoft word
  • Expressions with word world
  • Expressions with word thing