Embedding CSV files

In this recipe, we will demonstrate how to embed the CSV file shown in the previous recipe, how to read and parse the data in that file, and ultimately how to display the data in the file.

Getting ready

Create a new project for this chapter and place the three datafiles from the previous recipe in the lib folder of the project (data.csv, data.xlsx and data.xml). Copy the Graph and Legend classes from the previous chapter into the src folder. We will be using those again.

If you didn't complete the chapter, you can just start from the example project supplied with the book.

To avoid excessive code, we will also use the StringHelper class from the Adobe ActionScript live docs that can be found at http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html#includeExamplesSummary. Create a class called StringHelper in the src folder and copy the code into it.

Now create a new Recipe1 class in the src folder of your project:

package  
{
    import flash.display.Sprite;
    public class Recipe1 extends Sprite
    {
      private var graph:Graph;
  
      public function Recipe1() 
      {
        graph = new Graph( -50, 550, 750, -50);
        addChild(graph);
        graph.drawHorizontalAxis(0, 0, 700, 50, ["0", "700"]);
        graph.drawVerticalAxis(0, 0, 500, 50, ["0", "250", "500"]);
      }

    }

}

This is the starting point of this recipe.

How to do it...

Follow these steps to load the CSV file and display its data:

  1. Create an empty line just before the declaration of the graph variable and place the cursor there.
  2. Open the lib folder in the project view. Right-click on the data.csv file and select Generate Embed Code. This will add the following line to the program:
    [Embed(source="../lib/data.csv", mimeType="application/octet-stream")]
  3. Under that line, add the class name to bind the embedded resource to:
    private var DataClass:Class;
  4. Now add a private function to the class that will parse the CSV file:
    private function parseCSV(text:String):Array
    {
      var data:Array = [];
      var lines:Array = text.split('
    '),
      for (var i:int = 0; i < lines.length; i++) 
      {
        if (stringHelper.trim(lines[i], '') == '')
        {
          continue;
        }
    
        var dataLine:Array = []
        var numbers:Array = lines[i].split(','),
        for (var j:int = 0; j < numbers.length; j++) 
        {
    dataLine.push(Number(stringHelper.trim(numbers[j], '')));
        }
        data.push(dataLine);
      }
      return data;
    }
  5. This function takes a string as an argument and creates a multi-dimensional number array and can be used in the constructor with all the methods we created in Chapter 1, Getting Started with Graph Drawing. For instance:
    var data:Array = parseCSV(new DataClass());
    for (var i:int = 0; i < data.length; i++)
    {
        graph.drawPoint(data[i][0], data[i][1]);
        graph.drawPoint(data[i][0], data[i][2], 0x9933ff);
    }

How it works...

Embedding resources is the easiest way to add items to your ActionScript program. You may remember we have used a similar approach to adding images when styling the graph. This time however, we embed a text document instead of an image.

Converting a file into its useable bits and pieces is called parsing. As you can see from the code, parsing a CSV is fairly straightforward, as mentioned in the following steps:

  1. Split the file in lines.
  2. Split every line at the comma (if your CSV file uses semicolons, you should adapt the code right here).
  3. Remove all the unnecessary whitespace around the number.
  4. These pieces are still strings, so we convert them to a number.
  5. Finally they are added to the data array.

Before trying to process a line, we check if the line is empty. In that case we skip the line (this is a precaution since many text editors add an empty line at the end of the file).

There's more...

Parsing text files can be a tricky thing. There are a few ways to make this more robust.

CSV parsing

Although CSV parsing is fairly easy, there are a few intricacies. If you want to follow the official standard, you are probably better off using an existing open source library instead of creating your own.

For instance, "csvlib" supports the RFC 4180 standard and can be found at http://code.google.com/p/csvlib/.

See also

If you are interested in text processing and want to try out a different approach of parsing CSV files, you can also use regular expressions (or regex) to split the file into its components.nstance, Taytay (http://taytay.com/?p=106) uses the following regex to parse CSV lines, and it complies with most of the official spec:

lines[i].split(/,(?=(?:[^"]*"[^"]*")*(?![^"]*"))/g)

More information on ActionScript's regular expression handling and the RegExp class can be found here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/RegExp.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.218.230