Flex – Export datagrid to excel spreadsheet with ASP

This blog post explains how to export a Flex DataGrid to an Excel spreadsheet using an ASP server.

The original file came from the tutorial I found here: http://www.saskovic.com/blog/?p=3.

My solution features an ASP file instead of PHP as an external as well as some additional modifications:
- Removed unnecessary escape slashes “\” to avoid the necessity of a stripslashes function
- Added a filename parameter to the loadDGInExcel function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package utils {
    /**
     * Simple script to convert a Datagrid to a HTML table and then
     * pass it on to an external excel exporter
     *
     * @author: S.Radovanovic (With help of Tracy Spratt through the post on
     *          http://www.cflex.net/showFileDetails.cfm?ObjectID=298&Object=File&ChannelID=1)
     *
     *      Modifications by Phil Melzer:
     *      - Removed unnecessary escape slashes "\" to avoid the necessity of a stripslashes function
     *      - Added a filename parameter in loadDGInExcel
     */
   

    //Libs that are mostly used
    //(only a number are necessary for the datagrid conversion and export)
    import mx.controls.Alert;
    import mx.core.UIComponent;
    import mx.core.Container;
    import mx.events.ItemClickEvent;
    import mx.utils.ObjectProxy;
    import flash.errors.*;
    import flash.events.*;
    import flash.external.*;       
    import flash.net.URLLoader;
    import flash.net.URLVariables;
    import flash.net.URLRequest;
    import flash.net.URLRequestMethod;
    import mx.controls.DataGrid;
   
    public class Datagrid2Excel {
       
        //The location of the excel export file
        public var urlExcelExport:String = "DataGrid2Excel.asp";
   
        /**
         * Convert the datagrid to a html table
         * Styling etc. can be done externally
         *
         * @param: dg Datagrid Contains the datagrid that needs to be converted
         * @returns: String
         */

        private function convertDGToHTMLTable(dg:DataGrid):String {
            //Set default values
            var font:String = dg.getStyle('fontFamily');
            var size:String = dg.getStyle('fontSize');
            var str:String = '';
            var colors:String = '';
            var style:String = 'style="font-family:'+font+';font-size:'+size+'pt;"';               
            var hcolor:Array;
           
            //Retrieve the headercolor
            if(dg.getStyle("headerColor") != undefined) {
                hcolor = [dg.getStyle("headerColor")];
            } else {
                hcolor = dg.getStyle("headerColors");
            }              
           
            //Set the htmltabel based upon knowlegde from the datagrid
            str+= '<table width="'+dg.width+'"><thead><tr width="'+dg.width+'" style="background-color:#' +Number((hcolor[0])).toString(16)+'">';
           
            //Set the tableheader data (retrieves information from the datagrid header             
            for(var i:int = 0;i<dg.columns.length;i++) {
                colors = dg.getStyle("themeColor");
                   
                if(dg.columns[i].headerText != undefined) {
                    str+='<th '+style+'>'+dg.columns[i].headerText+'</th>';
                } else {
                    str+='<th '+style+'>'+dg.columns[i].dataField+'</th>';
                }
            }
            str += '</tr></thead><tbody>';
            colors = dg.getStyle("alternatingRowColors");
           
            //Loop through the records in the dataprovider and
            //insert the column information into the table
            for(var j:int =0;j<dg.dataProvider.length;j++) {                   
                str+='<tr width="'+Math.ceil(dg.width)+'">';
                   
                for(var k:int=0; k < dg.columns.length; k++) {
                   
                    //Do we still have a valid item?                       
                    if(dg.dataProvider.getItemAt(j) != undefined && dg.dataProvider.getItemAt(j) != null) {
                       
                        //Check to see if the user specified a labelfunction which we must
                        //use instead of the dataField
                        if(dg.columns[k].labelFunction != undefined) {
                            str += '<td width="' + Math.ceil(dg.columns[k].width) + '" ' + style + '>' + dg.columns[k].labelFunction(dg.dataProvider.getItemAt(j), dg.columns[k].dataField) + '</td>';
                           
                        } else {
                            //Our dataprovider contains the real data
                            //We need the column information (dataField)
                            //to specify which key to use.
                            str += '<td width="' + Math.ceil(dg.columns[k].width) + '" ' + style + '>' + dg.dataProvider.getItemAt(j)[dg.columns[k].dataField] + '</td>';
                        }
                    }
                }
                str += '</tr>';
            }
            str+='</tbody></table>';
       
            return str;
        }
       
        /**
         * Load a specific datagrid into Excel
         * This method passes the htmltable string to an backend script which then
         * offers the excel download to the user.
         * The reason for not using a copy to clipboard and then javascript to
         * insert it into Excel is that this mostly will fail because of the user
         * setup (Webbrowser configuration).
         *
         * @params: dg Datagrid The Datagrid that will be loaded into Excel, fn String The name of the excel file to create
         */

        public function loadDGInExcel(dg:DataGrid, fn:String="datagrid"):void {

            //Pass the htmltable in a variable so that it can be delivered
            //to the backend script
            var variables:URLVariables = new URLVariables();
            variables.htmltable = convertDGToHTMLTable(dg);
            variables.filename = fn;
           
            //Setup a new request and make sure that we are
            //sending the data through a post
            var u:URLRequest = new URLRequest(urlExcelExport);
            u.data = variables; //Pass the variables
            u.method = URLRequestMethod.POST; //Don't forget that we need to send as POST
           
            //Navigate to the script
            //We can use _self here, since the script will through a filedownload header
            //which results in offering a download to the user (and still remaining in you Flex app.)
                    flash.net.navigateToURL(u,"_self");
            }
    }
}

Datagrid2Excel.as

And here is the external ASP file.

1
2
3
4
5
6
7
<%@  language="JavaScript" %>
<%
Response.ContentType = "application/octet_stream";
Response.AddHeader("ETag", "etagforie7download");
Response.AddHeader("Content-Disposition", "attachment; filename=" + Request.Form("filename") + ".xls");
Response.Write("<html><body>" + Request.Form("htmltable") + "</body></html>");
%>

DataGrid2Excel.asp

Tags: , ,

3 Responses to “Flex – Export datagrid to excel spreadsheet with ASP”

  1. ENRIQUE says:


    PillSpot.org. Canadian Health&Care.Special Internet Prices.No prescription online pharmacy.Best quality drugs. Low price pills. Buy pills online

    Buy:Soma.Cialis Soft Tabs.Tramadol.Viagra.Zithromax.Propecia.Super Active ED Pack.Cialis Professional.VPXL.Viagra Super Force.Viagra Super Active+.Levitra.Maxaman.Viagra Professional.Viagra Soft Tabs.Cialis Super Active+.Cialis….

  2. RAFAEL says:


    Pillspot.org. Canadian Health&Care.Special Internet Prices.No prescription online pharmacy.Best quality drugs. No prescription drugs. Order pills online

    Buy:Valtrex.Human Growth Hormone.Retin-A.Arimidex.Lumigan.Zyban.Synthroid.100% Pure Okinawan Coral Calcium.Actos.Prednisolone.Nexium.Accutane.Petcam (Metacam) Oral Suspension.Mega Hoodia.Prevacid.Zovirax….

Leave a Reply