Home > Advanced, FLEX > Simple CSV Exporter

Simple CSV Exporter

Hi guys, when i wanted to write a  post about this topic i was clear that i am not gonna do something which no one would have done before but it will at least save others time who doesn’t familiar with CSV export. Unfortunately we doesn’t have enough example available for CSV export in web and that’s what compromised myself to write a post about it.

Now check out the simple CSV exporter utility class pasted below. Its a singleton class and  has method named exportCSV which writes the object from the collection to a chosen CSV (string delimited file) file. But when i wrote the class, i had two things in mind that not always developers want to write all the properties of an object, most of the times it will be only few so i wrote this method which receives array of properties of an object in the order it has to be written. And also the string delimiter will different from the requirements of an application so one can also pass the string delimiter they would like to use against the default string delimiter (“\t”) .

package
{
  import flash.filesystem.File;
  import flash.filesystem.FileMode;
  import flash.filesystem.FileStream;

  public class CSVExporter
  {
    protected var file : File;
    protected var dataProvider : Array;
    protected var columnFields : Array;
    protected var fileStream : FileStream;
    protected var columnSeparator : String;

    protected static var NEW_LINE : String = "\n";
    private static var instance : CSVExporter;

    public static function getInstance():CSVExporter
    {
      if(instance == null)
        instance = new CSVExporter();
      return instance;
    }

    public function exportCSV(file : File,
                              dataProvider : Array,
                              columnFields : Array,
                              columnSeparator : String = "\t")
    {
      this.file = file;
      this.dataProvider = dataProvider;
      this.columnFields = columnFields;
      this.columnSeparator = columnSeparator;

      fileStream = new FileStream();
      fileStream.open(file, FileMode.WRITE);
      writeHeaderRow();
      parseDataProvider();
      fileStream.close();
    }

    protected function writeHeaderRow():void
    {
      for(var index = 0; index < columnFields.length; index++)
      {
        fileStream.writeUTFBytes(columnFields[index].toUpperCase());

        if(index != columnFields.length - 1)
          fileStream.writeUTFBytes(this.columnSeparator);
      }
      fileStream.writeUTFBytes(NEW_LINE);
    }

    protected function parseDataProvider():void
    {
      for(var index : int = 0; index < this.dataProvider.length; index++)
      {
        writeDataRow(dataProvider[index] as Object);
        if(index != dataProvider.length-1)
          fileStream.writeUTFBytes(NEW_LINE);
      }
    }

    protected function writeDataRow(data : Object):void
    {
      for(var index : int = 0; index < columnFields.length; index++)
      {
        var property : String = columnFields[index] as String;

        if(data[property] != null)
          fileStream.writeUTFBytes(data[property] as String);

        if(index != columnFields.length-1)
          fileStream.writeUTFBytes(columnSeparator);
      }
    }
  }
}

Here it goes, the method which invokes CSV Exporter :-

protected function writeCollection():void
{
  var dataCollection : ArrayCollection = new ArrayCollection();
  dataCollection.addItem({name : "Sachin", age : 35, role : "All-rounder", state : "Mumbai"});
  dataCollection.addItem({name : "Sehwag", age : 30, role : "All-rounder", state : "Delhi"});
  dataCollection.addItem({name : "Gambhir", age : 25, role : "Batsmen", state : "Delhi"});
  dataCollection.addItem({name : "Yuvraj", age : 28, role : "All-rounder", state : "Punjab"});
  dataCollection.addItem({name : "Virat", age : 24, role : "Batsmen", state : "Delhi"});
  dataCollection.addItem({name : "Dhoni", age : 25, role : "Wicket-keeper",state : "Jharkand"});

  var  file : File = File.desktopDirectory.resolvePath("friends.csv");
  CSVExporter.getInstance().exportCSV(file, dataCollection.toArray(), ["name","role","state"]);
}

I hope you would have got brief insight about CSV exporting at the end of this post. If this post dint impress you for what you have looked for, please drop your comments i try to look out a solution for your need. Thank you for reading this post.

Advertisements
  1. January 5, 2010 at 5:56 pm

    Happy New year my friend,
    i am regular reader of your blog. First of all thanks to write about drag and drop it saves my time. what i am expecting from u is please write about Component life. it will be useful for us

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: