本例实现将flex中的数据利用as3xls-1[1].0.swc导出到excel文件中
flash.filesystem.*
需要flex AIR工程环境
在flex web application 工程环境下,没有flash.filesystem.*
废话不多说了,代码拿来
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.events.CloseEvent;
import mx.controls.CheckBox;
import mx.controls.Alert;
import com.as3xls.xls.ExcelFile;
import com.as3xls.xls.Sheet;
import flash.filesystem.*;
[Bindable]
private var dp:Array = [
{idx:1, names: "test1", sex: "b" },
{idx:2, names: "test2", sex: "g" }
];
public function doSelect(o:Object):void
{
Alert.show("行的数据分别是:"+o.idx+"/"+o.names+"/"+o.sex);
}
private function showWithCloseHandler(){
Alert.show("是否删除这条数据","提示",(Alert.OK|Alert.NO),null,showalert);
}
public function showalert(event:CloseEvent):void{
if(event.detail == Alert.OK){
Alert.show("你点击了OK按钮");
}else {
Alert.show("你点击了NO按钮");
}
}
private var sheet:Sheet;
private function onCreate():void {
var excelFile:ExcelFile = new ExcelFile();
sheet = new Sheet();
sheet.resize(10, 10);
sheet.setCell(0, 0, "Today's date:");
sheet.setCell(0, 1, new Date());
excelFile.sheets.addItem(sheet);
var mbytes:ByteArray = excelFile.saveToByteArray();
var stream:FileStream = new FileStream();
var docsDir:File = File.documentsDirectory.resolvePath("abc.xls"); // 定死文件名
try
{
docsDir.browseForSave("Save As");
docsDir.addEventListener(Event.SELECT, saveData);
}
catch (error:Error)
{
trace("Failed:", error.message)
}
function saveData(event:Event):void
{
var newFile:File = event.target as File;
if (!newFile.exists)
{
var stream:FileStream = new FileStream();
stream.open(newFile, FileMode.WRITE);
stream.writeBytes(mbytes);
// 写文件流
stream.close();
}
}
}
]]>
</mx:Script>
<mx:Panel>
<mx:Button label="导出" click="onCreate()"/>
<mx:Button label="提示" click="showWithCloseHandler()"/>
<mx:DataGrid id="dg1" dataProvider ="{dp}">
<mx:columns>
<mx:DataGridColumn width="20" headerText="" >
<mx:itemRenderer>
<mx:Component>
<mx:CheckBox change=" {outerDocument.doSelect(data as Object)} " />
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
<mx:DataGridColumn headerText="names" dataField="names" width="200" />
<mx:DataGridColumn headerText="sex" dataField="sex" width="300" />
</mx:columns>
</mx:DataGrid>
</mx:Panel>
</mx:WindowedApplication>