导出Excel辅助as类:
/**
* Simple script to convert a Datagrid to a HTML table and then
* pass it on to an external excel exporter
*
*/
//Libs that are mostly used
//(only a number are necessary for the datagrid conversion and export)
import flash.errors.*;
import flash.events.*;
import flash.external.*;
import flash.net.URLRequest;
import flash.net.URLVariables;
/**
* 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+'" border="1"><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("alternatingItemColors");
//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
* @params: url String The location of the excel export file
*/
private function loadDGInExcel(dg:DataGrid,url:String):void {
//后后台交互
var variables:URLVariables = new URLVariables();
variables.htmltable= convertDGToHTMLTable(dg);
//设置新的请求并发送
var u:URLRequest = new URLRequest(url);
u.data = variables;
u.method = URLRequestMethod.POST; //请求方式
//导航到脚本
//我们在这里可以使用_self中,因为脚本会通过filedownload头
//这会导致在提供给用户下载(现在仍然在你的Flex应用程序剩余。)
navigateToURL(u,"_self");
}
测试文件源码:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
initialize="myService.send()"
fontSize="12" viewSourceURL="srcview/index.html">
<mx:Script source="utils.as"/>
<!--<mx:Style source="DGtoExcel.css"/>-->
<mx:Script>
<![CDATA[
import mx.events.ItemClickEvent;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.collections.ArrayCollection;
[Bindable]
private var myAC:ArrayCollection;
private function faultHandler(event:FaultEvent):void
{
Alert.show(event.fault.faultString, event.fault.message);
}
// Function to filter out all items with gender
private function maleFilterFunc(item:Object):Boolean {
return item.gender == 1;
}
// Function to apply the filter function the ICollectionView.
private function filterMale():void {
myAC.filterFunction = maleFilterFunc;
//Refresh the collection view to apply the filter.
myAC.refresh();
}
// Function to filter out all items with gender
private function femaleFilterFunc(item:Object):Boolean {
return item.gender == 0;
}
// Function to apply the filter function the ICollectionView.
private function filterFemale():void {
myAC.filterFunction = femaleFilterFunc;
//Refresh the collection view to apply the filter.
myAC.refresh();
}
// Function to Reset the view to its original state.
private function resetAC():void {
myAC.filterFunction = null;
//Refresh the collection view.
myAC.refresh();
}
// Event handler function to display the selected button
private function filterHandler(event:ItemClickEvent):void {
switch(event.currentTarget.selectedValue){
case 1:
filterMale();
break;
case 0:
filterFemale();
break;
case 2:
resetAC();
break;
default:
break;
}
}
]]>
</mx:Script>
<mx:HTTPService id="myService"
showBusyCursor="true"
url="data/student.xml"
result="myAC = event.result.item.student"
fault="faultHandler(event)"/>
<mx:HBox>
<mx:RadioButtonGroup id="gendertype" itemClick="filterHandler(event);"/>
<mx:RadioButton groupName="gendertype" id="rbMale" value="1" label="男" />
<mx:RadioButton groupName="gendertype" id="rbFemale" value="0" label="女" />
<mx:RadioButton groupName="gendertype" id="rbAll" value="2" label="所有" />
</mx:HBox>
<mx:DataGrid id="myDG" width="100%" rowCount="20"
dataProvider="{myAC}" >
<mx:columns>
<mx:DataGridColumn headerText="学好" dataField="studentID"/>
<mx:DataGridColumn headerText="姓名" dataField="name"/>
<mx:DataGridColumn headerText="性别" dataField="gender" width="50"/>
<mx:DataGridColumn headerText="生日" dataField="birthday" />
<mx:DataGridColumn headerText="班级" dataField="className"/>
</mx:columns>
</mx:DataGrid>
<mx:Button label="导出为Excel" click="loadDGInExcel(myDG,'http://localhost:8088/OutExcel/exportExcel.jsp');" />
</mx:Application>
java 后台:
<%@ page language="java"%>
<%@ page contentType="application/msexcel;charset=UTF-8" pageEncoding="UTF-8" %>
<%
request.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition","attachment;filename=test.xls");
String str=request.getParameter("htmltable");
out.print(str);
%>