Exporting data as CSV to import in Excel

Until now, we've always read files and displayed them. In the final recipes of the chapter, we will show how to export the data that we have available inside the program. This can be useful if you want to allow further processing of the data in other programs.

For instance, imagine that you import and process data from a REST service. Users may want to take that data out of the application and use it in Excel to perform their own calculations or create a custom graph.

This recipe looks at exporting to the CSV format that can be used to load the data in Excel and other spreadsheet programs.

Getting ready

For this recipe, we will start from a simple data array, but of course the data could be coming from anywhere.

Start by creating a Recipe7 document class:

package  
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.net.FileReference;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;

    public class Recipe7 extends Sprite
    {
        private var graph:Graph;
        private var data:Array = [[0,20],[50,70],[100,0],[150,150],[200,300],[250,200],[300,400],[350,20],[400,60],[450,250],[500,90],[550,400],[600,500],[650,450],[700,320]];

        public function Recipe7() 
        {
            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"]);

            for (var i:int = 0; i < data.length; i++)
            {
                graph.drawPoint(data[i][0] + 4, data[i][1]);
            }
        }

    }

}

This should display a familiar point graph.

How to do it...

Follow the next steps to create a CSV file that can be used in Excel:

  1. We are going to trigger the file saving through a mouse click. Therefore, in the Recipe7 constructor add the following code:
    var loadText:TextField = new TextField();
    loadText.text = "click here to save to file";
    loadText.autoSize = TextFieldAutoSize.LEFT;
    loadText.addEventListener(MouseEvent.CLICK, onClick);
    addChild(loadText);
  2. The FileReference class will once again be our gateway to the user's filesystem. So we add a private variable to the class:
    private var saveFile:FileReference;
  3. The onClick method is where the bulk of the action is. Add it to the Recipe7 class:
    private function onClick(event:MouseEvent):void
    {
        saveFile = new FileReference();
        saveFile.addEventListener(Event.COMPLETE, onComplete);
        var csv:String = "";
        for (var i:int = 0; i < data.length; i++)
        {
            var line:String = "";
            for (var j:int = 0; j < data[i].length; j++)
            {
                line += data[i][j];
                if (j != data[i].length - 1) 
                {
                line += ","; // international users: replace with ; 
             }
         }
         csv += line + "
    ";
      }
    
      saveFile.save(csv, "data.csv");
    }
  4. Finally, for demonstration purposes, we also add an onComplete method that fires when the file is saved:
    private function onComplete(event:Event):void
    {
        trace("file was saved");
    }
  5. If you run the program, you can click on the save file text. This will show a popup with a default filename proposed. You can change it if you like. After clicking on the Save button the file will be created.
  6. This file should open without issues in Excel.

How it works...

The FileReference class is a class you will be using in almost any case, when you want to interact with the user's files. It allows you to create a popup file chooser for various purposes. We've already seen the load method. In this recipe, we use it to save a file.

The onClick method in the recipe is a mirror of the parseCSV method that was used in the previous recipes. It combines the elements of the data structure into the text format. It creates lines for every datapoint and puts the individual elements in the file, separated by commas (or semicolons if that's what your version of Excel accepts).

The onComplete method can be used to give visual feedback that the file was saved successfully. Keep in mind that most of the users will not see the output that trace generates. So for a real application, you will probably want to show a text field or something similar in the interface.

There's more...

When using CSV files, there are a few things to take into consideration.

Semicolon or comma

The same CSV issue that we've experienced before pops up here too. If you expect to serve international customers, you should make sure they have an option to switch the CSV separator.

CSV header

If you want to indicate what the data actually is, you may want to insert a first line in the CSV file with comma-separated names for each of the columns. This can make it easier to understand and process the file in other applications.

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

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