Flex把datagrid的内容导出到Excel

本文介绍如何使用Flex将DataGrid中的数据导出至Excel文件。通过自定义函数实现数据收集、格式化并最终保存为Excel文件的过程。适用于希望快速实现此功能的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

flex 把datagrid的内容导出到Excel
文章分类:Flash编程

SDK要3.4以上的版本:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
import com.as3xls.xls.Cell;
import mx.collections.ArrayCollection;

import com.as3xls.xls.Sheet;
import com.as3xls.xls.ExcelFile;

private var fileReference:FileReference;
private var xls:Class;
private var sheet:Sheet;

[Bindable]
private var fields:Array = new Array();

[Bindable]
private var ItemDGDataProvider:ArrayCollection = new ArrayCollection([
{name:"Item1",value:"21",qty:"3",cost:"12.21", apples: "1"},
{name:"Item2",value:"20",qty:"4",cost:"12.22", apples: "1"},
{name:"Item3",value:"22",qty:"5",cost:"12.23", apples: "1"},
{name:"Item4",value:"23",qty:"2",cost:"12.24", apples: "1"}
]);

private function fileReference_Cancel(event:Event):void
{
fileReference = null;
}

private function exportToExcel():void
{
sheet = new Sheet();
var dataProviderCollection:ArrayCollection = rebateByItemDG.dataProvider as ArrayCollection;
var rowCount:int = dataProviderCollection.length;
sheet.resize(rowCount + 1,rebateByItemDG.columnCount);
var columns:Array = rebateByItemDG.columns;
var i:int = 0;
for each (var field:DataGridColumn in columns){
fields.push(field.dataField.toString());
sheet.setCell(0,i,field.dataField.toString());
i++;
}

for(var r:int=0; r < rowCount; r++)
{
var record:Object = dataProviderCollection.getItemAt(r);
/*insert record starting from row no 2 else
headers will be overwritten*/
insertRecordInSheet(r+1,sheet,record);
}
var xls:ExcelFile = new ExcelFile();
xls.sheets.addItem(sheet);

var bytes: ByteArray = xls.saveToByteArray();
var fr:FileReference = new FileReference();
fr.save(bytes,"SampleExport.xls");
}
private function insertRecordInSheet(row:int,sheet:Sheet,record:Object):void
{
var colCount:int = rebateByItemDG.columnCount;
for(var c:int; c < colCount; c++)
{
var i:int = 0;
for each(var field:String in fields){
for each (var value:String in record){
if (record[field].toString() == value)
sheet.setCell(row,i,value);
}
i++;
}
}
}
]]>
</mx:Script>
<mx:VBox width="100%" height="100%">
<mx:Form>
<mx:FormItem label="Export Datagrid items to Excel?" fontWeight="bold">
<mx:Form>
<mx:HBox width="100%" verticalAlign="middle">
<mx:DataGrid id="rebateByItemDG" includeInLayout="true" visible="true" dataProvider="{ItemDGDataProvider}" width="100%" editable="true"/>
<mx:Button label="Export To Excel" click="exportToExcel();"/>
</mx:HBox>
</mx:Form>
</mx:FormItem>
</mx:Form>
</mx:VBox>
</mx:Application>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值