方法一:
1.Excel导出主要代码:
try
{
var bytes: ByteArray = new ByteArray();
bytes.writeMultiByte(DataGridExporter.exportSCV(dataGrid),"cn-gb");
var fr:FileReference = new FileReference();
var date:Date = new Date();
var dateTime:String = date.fullYear.toString() + "年" + (Number(date.month) + 1).toString() + "月" + date.date.toString() + "日";
var excelName:String = dateTime + filename;
fr.save(bytes,excelName);
}
catch(e:Error)
{
MapUni.errorWindow(e.toString());
}
2.调用的类DataGridExporter:
public class DataGridExporter
{
public function DataGridExporter()
{
}
public static function exportSCV(dg:DataGrid,csvSeparator:String="\t",lineSeparator:String="\n"):String
{
var dataStr:String="";
var columns:Array=dg.columns;
var columnCount:int=columns.length;
var column:DataGridColumn;
var header:String="";
var headerGenerated:Boolean=false;
var dataProvider:Object=dg.dataProvider;
var rowCount:int=dataProvider.length;
var dp:Object=null;
var cursor:IViewCursor=dataProvider.createCursor();
var j:int = 0;
while(!cursor.afterLast)
{
var obj:Object=null;
obj = cursor.current;
for(var k:int = 0; k <columnCount;k++)
{
column=columns[k];
if(!column.visible)
{
continue;
}
dataStr += "\""+column.itemToLabel(obj)+"\"";
if(k<(columnCount-1))
{
dataStr+=csvSeparator;
}
if(!headerGenerated)
{
header+="\""+column.headerText+"\"";
if(k<(columnCount-1))
{
header+=csvSeparator;
}
}
}
headerGenerated=true;
if(j<(rowCount-1))
{
dataStr+=lineSeparator;
}
j++;
cursor.moveNext();
}
dataProvider=null;
columns=null;
column=null;
return (header+"\r\n"+dataStr);
}
方法二:
1.var excelFactory:SaveExcelField = new SaveExcelField();
excelFactory.ExportToExcel(dataGrid, "hendText",true);
public function ExportToExcel(dataGrid:DataGrid,filename:String, allData:Boolean):void
{
try
{
var fields:Array = new Array();
var sheet:Sheet = new Sheet();
var dataProviderCollection:ArrayCollection =dataGrid.dataProvider as ArrayCollection;
var i:int = 0;
var columns:Array = dataGrid.columns;
var rowCount:int = dataProviderCollection.length;
if(allData)
{
sheet.resize(rowCount+1,dataGrid.columnCount);
columns.pop();
}
else
{
sheet.resize(rowCount+1,dataGrid.columnCount);
/*
for (var m:int=0;m<columns.length;m++)
{
var field1:DataGridColumn=columns[m] as DataGridColumn;
//var field:DataGridColumn in columns
fields.push(field1.dataField.toString());
sheet.setCell(0,i,field1.headerText.toString());
i++;
}*/
}
//sheet.resize(rowCount+1,dataGrid.columnCount-1);
for each (var field:DataGridColumn in columns)
{
fields.push(field.dataField.toString());
sheet.setCell(0,i,field.headerText.toString());
i++;
}
for(var r:int=0;r<rowCount;r++)
{
var record:Object =dataProviderCollection.getItemAt(r);
insertRecordInSheet(r+1,sheet,record,fields);
}
var xls:ExcelFile = new ExcelFile();
xls.sheets.addItem(sheet);
var bytes: ByteArray = xls.saveToByteArray();
var fr:FileReference = new FileReference();
fr.save(bytes,filename);
}
catch(e:Error)
{
MapUni.errorWindow(e.toString());
}
}
flex 导出Excel功能实现