Avg. Rating 2.7

Problem

You want to give the user the possibility to export to Excel.

Solution

Convert the datagrid data to CSV or TSV format then use System.setClipboard() in order to copy the data to the clipboard.

Detailed explanation

With Excel, you can use comma separated values (CSV) or tab separated values (TSV) for import. In this recipe, we will use tabulations.

We will write a method called when the user presses an Export to Excel button.
       
In ActionScript, a tabulation character is represented with the following escape sequence: \t, a line break is represented by: \n
       
You separate each column header name from the next with a tabulation character.
You also separate each column value from the next with a tabulation character.
The end of each row is marked by a linebreak.

You copy a string to the clipboard by invoking the setClipboard(String) static method on the System class.

In the example, this.model.sales is the dataprovider for our datagrid.
       
        import flash.system.System;
        import com.mycompany.dto.SaleDTO;
       
        public function exportAsTSVtoClipBoard():void
        {
            var TSVString:String = "";

            // Run through each field to create the column headers row

            TSVString += "Buyer name" + "\t";
            TSVString += "Buyer id" + "\t";
            TSVString += "Buyer address" + "\t";
            TSVString += "Gross Amount" + "\t";
            TSVString += "VAT AMount" + "\t";
            TSVString += "Net Amount" + "\n";
           
            // Line break
            TSVString += "\t" + "\t" + "\t" + "\t" + "\t" + "\n";
           
            // Run through each datagrid row
           
            for each(var item:SaleDTO in this.model.sales)
            {
                TSVString += item.buyerName + "\t";
                TSVString += item.buyerId + "\t";
                TSVString += item.buyerAddress + "\t";
                TSVString += this.numberFormatter.format(item.grossAmount) + "\t";
                TSVString += this.numberFormatter.format(item.vatAmount) + "\t";
                TSVString += this.numberFormatter.format(item.netAmount) + "\n";
            }
               
            // Copy the TSV string to the clipboard
            System.setClipboard(TSVString);
        }

You assign the exportAsTSVtoClipBoard() method as the event handler for the click event of your Export to Excel button.
 

 

Report abuse

Related recipes