Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export data to a csv file with iOS?

Tags:

ios

csv

My application has a function which can export some data to a csv file, and then copied to PC. What api to use to implement this function?

like image 462
Joey Avatar asked Jul 21 '09 14:07

Joey


2 Answers

You can also do something like:

[[array componentsJoinedByString:@","] writeToFile:@"components.csv" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

You can use combinations of this to put together a CSV (append the output of one array for the column names to one array for the values, etc).

Of course, you have to be careful to put quotes around values that already contain a comma, and to then escape any quotes in the value.

like image 132
Joe V Avatar answered Nov 15 '22 07:11

Joe V


Exporting to a csv file is typically not very difficult. Importing it is much trickier to do correctly.

to export data to a csv file do the following: (pseudocode)

1) open file 2) export column names

 int cnt=0;
 foreach(String columnname in columns)
 {
      if(cnt!=0) //write the delimiter
      {
           file.WriteText(",");  //could also be a tab delimiter
      }
      file.WriteText(columnName) //write columnname
      cnt++;
 }

3) write all the data to the csv

 foreach(StringArray row in rows)
 {
      cnt=0;
      foreach(String fieldValue in row)
      {
           if(cnt!=0) //write the delimiter
           {
                file.WriteText(",");  //could also be a tab delimiter
           }
           file.WriteText(fieldValue) //write fieldvalue
           cnt++;
      }
 }

please beware of the fact that the delimiter might also be part of the value. If this happens, the complete field should be enclosed in double quotes.

like image 25
Toad Avatar answered Nov 15 '22 07:11

Toad