xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”>
import com.as3xls.xls.ExcelFile;
import com.as3xls.xls.Sheet;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.CheckBox;
[Bindable]
private var dp:Array=[
{studentID:1,name:”2ssdl”,gender:”为001″,birthday:”4区”,className:”5清道夫却无法”},
{studentID:2,name:”2士大”,gender:”1色调”,birthday:”4却”,className:”5为去去”},
{studentID:3,name:”2访问”,gender:”1色调”,birthday:”飞4″,className:”访问5″},
{studentID:4,name:”访问2″,gender:”0色调”,birthday:”4却”,className:”为5″},
{studentID:5,name:”2各位”,gender:”0色调”,birthday:”4飞”,className:”5为”}];
private function onCreate(dg:DataGrid):void
{
var rowCount:int=dg.dataProvider.length;
var colCount:int=dg.columnCount;
var sheet:Sheet=new Sheet();
sheet.resize(rowCount+1,colCount); //设置表格的范围
var fields:Array=new Array();//用来保存字段
for(var i:int=0; i< colCount;i++)
{
sheet.setCell(0,i,dg.columns[i].headerText.toString());//表格第0行设置字段名
fields.push(dg.columns[i].dataField.toString());
}
for(var i:int=0; i< rowCount;i++)
{
var record:Object=dg.dataProvider[i];//获取某行
insertRecordInSheet(i+1,sheet,record);
}
var excelFile:ExcelFile=new ExcelFile();//新建excel文件
excelFile.sheets.addItem(sheet);//把表格添加入excel文件中
var mbytes:ByteArray=excelFile.saveToByteArray();
var file:FileReference=new FileReference();
file.save(mbytes,”测试文件.xls”); // 定死文件名
file.addEventListener(Event.COMPLETE, function (){
Alert.show(“保存成功”);
});
function insertRecordInSheet(row:int,sheet:Sheet,record:Object):void
{
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++;
}
}
}
}
]]>