6

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joey
  • 149
  • 1
  • 1
  • 8

4 Answers4

11

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.

Joe V
  • 369
  • 3
  • 8
  • 1
    What should i do if i want to convert my database table into a csv file. So if the user opens the file in excel sheet, he can view the item in a table form – Warrior Mar 02 '11 at 13:16
2

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.

Toad
  • 15,593
  • 16
  • 82
  • 128
  • There's a great way to escape delimiter characters at this repo: http://bitbucket.org/fourplusone/fourcsv – Z S Aug 12 '10 at 18:58
0
NSData *data=[[arr componentsJoinedByString:@","] writeToFile:@"Bhavesh.csv" atomically:YES encoding:NSUTF8StringEncoding error:NULL];
[mail addAttachmentData:data mimeType:@"text/csv" fileName:@"Bhavesh.csv"];
Bhavesh Nayi
  • 3,626
  • 1
  • 27
  • 42
  • `- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error` method returns a `BOOL` value not `NSData`. – TheTiger Apr 26 '14 at 08:36
0

Here is a full function that does the job (Swift 3):

    func write(theseArrays arrays: [[String]], withTheseHeaders headers: [String], toFile filename: String) {

    let numCollumns = arrays.count
    let numRows = arrays.first!.count
    var output = "\(headers.joined(separator: ", "))\n"

    for r in 0...numRows-1 {
        var row = ""
        for c in 0...numCollumns-1 {
            row = c == 0 ? arrays[c][r] : row.appending(",  \(arrays[c][r])")
        }
        output = output.appending("\(row)\n")
    }

    let localDocumentsURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: .userDomainMask).last
    let myLocalFile = localDocumentsURL?.appendingPathComponent(filename)

    guard myLocalFile != nil else {
        print("----------- Couldn't create local file!")
        return
    }

    do {
        try output.write(to: myLocalFile!, atomically: true, encoding: String.Encoding.utf8)
    }
    catch let error as NSError {
        print(error.localizedDescription)
        return
    }
    print("Wrote CSV to: \(myLocalFile!)")

}
RawMean
  • 8,374
  • 6
  • 55
  • 82