Flex/Air将DataGrid数据导出为CSV/Excel格式

本文介绍了如何使用Flex框架将DataGrid数据导出为HTML样式并复制到剪切板,然后通过JavaScript在浏览器中打开并保存为Excel文件,或者将数据转换为CSV文件直接在Excel中打开。还提供了使用Air2.0的新特性和as3xlslibrary创建Excel表格的示例。
 

综合网上对这个问题的讨论,大致有两种思路。一种是:将DataGrid数据经过封装变为html格式,输出到系统剪切板中,通过调用JavaScript将数据写入Excel中,调用浏览器打开,浏览之后,保存。第二种:是将DataGrid数据转换为为CSV(逗号分隔值文件)文件,用Excel打开。同时搜素到一片文章,http://coenraets.org/blog/2009/11/open-in-excel-another-air-2-mini-sample/,在该文章中,作者实现了一个Demo,提到用Air2.0的新特性可以直接快速在Excel中打开DataGrid中的数据,通过使用
File.openWithDefaultApplication()方法,同时利用as3xls library创建 the Excel spreadshee。我现在仍然使用Air1.5,这种实现就先记下,以后在详细看看。

第一种方法原文http://www.cflex.net/showfiledetails.cfm?ObjectID=298

直接上代码:ACTION SCRIPT FOR YOUR FLEX APP

function doCopy(dg)
{
var font = dg.getStyle('fontFamily');
var size = dg.getStyle('fontSize');
var hcolor ;
if(dg.getStyle("headerColor") != undefined) hcolor = [dg.getStyle("headerColor")];
else hcolor = dg.getStyle("headerColors");
var str:String = '<html><body><table width="'+dg.width+'"><thead><tr width="'+
         dg.width+'" style="background-color:#' +Number((hcolor[0])).toString(16)+'">';
for(var i=0;i<dg.__columns.length;i++)
{
var colors = dg.getStyle("themeColor");
var style = 'style="font-family:'+font+';font-size:'+size+'pt;"';

if(dg.__columns[i].headerText != undefined)
{
str+="<th "+style+">"+dg.__columns[i].headerText+"</th>";
}
else
{
str+= "<th "+style+">"+dg.__columns[i].columnName+"</th>";
}
}
str += "</tr></thead><tbody>";
var colors = dg.getStyle("alternatingRowColors");
for(var j=0;j<dg.length;j++)
{
str+="<tr width=\""+Math.ceil(dg.width)+"\" style='background-color:#" +Number((colors[j%colors.length])).toString(16)+"'>";
var style = 'style="font-family:'+font+';font-size:'+size+'pt;"';

for(var i=0;i<dg.__columns.length;i++)
{
if(dg.getItemAt(j) != undefined && dg.getItemAt(j) != null)
if(dg.__columns[i].labelFunction != undefined)
str += "<td width=\""+Math.ceil(dg.__columns[i].width)+"\" "+style+">"+
dg.__columns[i].labelFunction(dg.getItemAt(j),dg.__columns[i].columnName)+"</td>";
else
str += "<td width=\""+Math.ceil(dg.__columns[i].width)+"\" "+style+">"+
dg.getItemAt(j)[dg.__columns[i].columnName]+"</td>";

}
str += "</tr>";
}
str+="</tbody></table></body></html>";
System.setClipboard(str);
}

function handleOnKeyUp()
{
if(Key.isDown(Key.CONTROL) &&Key.getCode() ==67)
{
mx.managers.CursorManager.setBusyCursor();
doCopy(grid);
                  // exchange 'grid' with the id of your datagrid you want copied
mx.managers.CursorManager.removeBusyCursor();
}
}
// only register interest if you want ctrl-c to process a copy of a datagrid.
// it's also ctrl + c (on key up, not down)
var obj:Object;
function registerKeyInterest()
{
if(obj == undefined)
{
   obj = new Object();
   obj.onKeyUp = mx.utils.Delegate.create(this,handleOnKeyUp);
}
   Key.addListener(obj);
}

function removeKeyInterest()
{
   Key.removeListener(obj);
}

function copyAndOpen(grid)
{
doCopy(grid);
getUrl("javascript:openExcel();");
}

// JAVASCRIPT for your HTML PAGE
<SCRIPT Language="JavaScript1.2">
var excel = null;
function openExcel()
{
try
{

if(excel == null)
{
excel = new ActiveXObject("Excel.Application");

}
var workbook = excel.Workbooks.Add();

workbook.Activate();
var worksheet = workbook.Worksheets("Sheet1");
worksheet.Activate();

worksheet.Paste();
excel.visible=true;

}catch(exception)
{
window.alert("Now you may Paste into an Excel SpreadSheet");
}
}
</SCRIPT>

第二种方法原文http://www.abdulqabiz.com/blog/archives/2007/08/03/datagriddataexporter-export-datagrid-data-as-csv/

DataGridDataExport.as

package com.abdulqabiz.utils
{
import mx.controls.DataGrid;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.collections.ArrayCollection;
import mx.collections.XMLListCollection;
import mx.collections.IList;
import mx.collections.IViewCursor;
import mx.collections.CursorBookmark;
public class DataGridDataExporter
{
public static function exportCSV(dg:DataGrid, csvSeparator:String="\t", lineSeparator:String="\n"):String
{
var data: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;
//loop through rows
while (!cursor.afterLast)
{
var obj:Object = null;
obj = cursor.current;
//loop through all columns for the row
for(var k:int = 0; k < columnCount; k++)
{
column = columns[k];
//Exclude column data which is invisible (hidden)
if(!column.visible)
{
continue;
}
data += "\""+ column.itemToLabel(obj)+ "\"";
if(k < (columnCount -1))
{
data += csvSeparator;
}
//generate header of CSV, only if it's not genereted yet
if (!headerGenerated)
{
header += "\"" + column.headerText + "\"";
if (k < columnCount - 1)
{
header += csvSeparator;
}
}
}
headerGenerated = true;
if (j < (rowCount - 1))
{
data += lineSeparator;
}
j++;
cursor.moveNext ();
}
//set references to null:
dataProvider = null;
columns = null;
column = null;
return (header + "\r\n" + data);
}
}
}

DataGridCSVExportExample.mxml

<?xml version="1.0"?>
<!-- DataGrid control example. -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import com.abdulqabiz.utils.DataGridDataExporter;
private function exportCSV ():void
{
console.text = DataGridDataExporter.exportCSV (dg);
}
]]>
</mx:Script>
<mx:XMLList id="employees">
<employee>
<name>Christina Coenraets</name>
<phone>555-219-2270</phone>
<email>ccoenraets@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>Joanne Wall</name>
<phone>555-219-2012</phone>
<email>jwall@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>Maurice Smith</name>
<phone>555-219-2012</phone>
<email>maurice@fictitious.com</email>
<active>false</active>
</employee>
<employee>
<name>Mary Jones</name>
<phone>555-219-2000</phone>
<email>mjones@fictitious.com</email>
<active>true</active>
</employee>
</mx:XMLList>
<mx:Panel title="DataGrid Control Example" height="100%" width="100%"
paddingTop="10" paddingLeft="10" paddingRight="10">
<mx:Label width="100%" color="blue"
text="Select a row in the DataGrid control."/>
<mx:DataGrid id="dg" width="100%" height="100%" rowCount="5" dataProvider="{employees}">
<mx:columns>
<mx:DataGridColumn dataField="name" headerText="Name"/>
<mx:DataGridColumn dataField="phone" headerText="Phone"/>
<mx:DataGridColumn dataField="email" headerText="Email"/>
</mx:columns>
</mx:DataGrid>
<mx:Button label="Export CSV" click="exportCSV ()"/>
<mx:TextArea id="console" width="100%" height="100%" />
</mx:Panel>
</mx:Application>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值