I’ve already written a python script that can convert a .csv file to a .xml file, which quite a few people seem to like. This is a good solution when you have a large file to convert.
But really, reading a small and simple csv file directly into Flex/Flash to use it in charts or display the contents in a DataGrid would be a “Nice To Have” solution. Plus, I’ve noticed that over the years I reuse my code and each time I add new functionality to it; now is the time to start with it !
So I made an AIR application ( for the simple reason that I load a local csv file) that does exactly that. The AIR app is called WeightManDesktop.
Since I know it’s a small file that I’m loading, it doesn’t matter that I load it completely into memory. For a larger file, in Python I would typically open the file for reading and read it line by line, processing each line as I go.
Using the File.browseForOpen AIR functionality, I read in the file selected by the user into a string and then process the content in a seperate function:
// Read in the selected file when the file is selected
private function openfileSRCHandler(event:Event):void{
fileStream.open(file, FileMode.READ);
content = String(fileStream.readUTFBytes(fileStream.bytesAvailable));
fileStream.close();
trace(“*** File loaded.”);
processContent();
}
Using the strings split function, I first split the string into seperate lines using the line seperator to split them. Each line thus becomes an Array. I then split each line into seperate content, again using the split function using commas to seperate them into the seperate items. These items are then added to an ArrayCollection that I’ve previously defined.
private function processContent():void {
//var ending:String = new String(“\n\g”);
// Split the whole file into lines
var values:Array;
var lines:Array = content.split(“\n”);
trace (“File split into ” + lines.length + ” lines”);
// Split each line into data content – start from 1 instead of 0 as this is a header line.
for ( var i: Number=1; i < lines.length; i++ ) {
var line: String = lines[i];
values = line.split(“,”);
trace (“line split in ” + values);
// Add values to arraycollection
linedata.addItem({date:values[0], weight:values[1], bmi:values[2], workout:values[3]});
And that’s it. Use the ArrayCollection as a dataprovider for your datagrid and Bob’s your Uncle !