Sunday, October 23, 2011

Exporting to excel with AS3XLS

Straight to the point. Code below shows how to do it. I guess I have added enough comments to explain the flow.


<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               width="100%" height="100%" initialize="init()">
    <fx:Script>
        <![CDATA[
import com.as3xls.biff.BIFFVersion;
import com.as3xls.biff.BIFFWriter;
import com.as3xls.biff.Record;
import com.as3xls.xls.ExcelFile;
import com.as3xls.xls.Formatter;
import com.as3xls.xls.Sheet;
import com.as3xls.xls.Type;

import mx.collections.ArrayCollection;
import mx.collections.ListCollectionView;
import mx.core.UIComponent;

import utils.ExcelExportUtil;

            private function init():void
   {
                var data:Array = new Array();
                for(var r:uint = 0; r < 50; r++)
{
                    data.push({col1:"Col1: " + r, col2:"Col2: " + r, col3:(r+1), col4:new Date(), col5:"Col5: " + r});
                }
                dataGrid.dataProvider = new ArrayCollection(data);
            }

    private function export():void
    {

var s:Sheet = new Sheet();
s.resize(datagrid.dataprovider.length, datagrid.columns.length);
                        var row:*;

for(var r:uint = 0; r < datagrid.dataprovider.length; r++)
{
for(var c:uint = 0; c < s.cols; c++)
{
row = datagrid.dataprovider.getItemAt(r);
rowValue = row[c];
s.setCell(r, c, (rowValue != null ? rowValue : ""));
}
}

var xls:ExcelFile = new ExcelFile();
xls.sheets.addItem(s);
var bytes:ByteArray = xls.saveToByteArray();

var fr:FileReference = new FileReference();
fr.save(bytes, "ExcelFile.xls");

    }
        ]]>
    </fx:Script>
    <s:layout>
        <s:VerticalLayout/>
    </s:layout>
    <s:Button label="Export" click="export()"/>
    <mx:DataGrid id="dataGrid" width="100%" height="100%" />
</s:Application>

1 comment :

sam said...

How can I make only the first row bold(consider first row as Header). When I tried to do that, the entire rows changing to bold