Search code examples
iphoneobjective-csqlitecsvmfmailcomposeviewcontroller

How to export SQLite file into CSV file with table format (excel sheet style)


in iphone app, I want to export a SQLite database file to CSV file. (later i attach this file in mail)

that too in a table format ( or exel-sheet format)

I have tried the following logic but it is not like a table format and huge differences in column alignments.

storedataBaseArray = [DataBase selectAllFromDB];

  NSString *CSVstring=@"SNO \t\t\t Index \t\t\t  Definition\n" ;

  NSString *CSVPath,*record;;

   NSString  *temporayCSV= @"" ;

  for(int i=0;i<storedataBaseArray.count ;i++)
  {


        record = [NSString stringWithFormat:@"%@, \t\t\t %@, \t\t\t %@, [ [storedContactsArray objectAtIndex:i] objectForKey"id"] ,  [ [storedContactsArray objectAtIndex:i] objectForKey"title"],  [ [storedContactsArray objectAtIndex:i] objectForKey"Definition"]];

   // NSString *role =[storedContactsArray objectAtIndex:i]  ;

    NSLog(@"%d",i);

    temporayCSV = [NSString stringWithFormat:@"%d  %@  \n ",(i+1),record];

       CSVstring = [CSVstring stringByAppendingFormat:temporayCSV];       
     NSLog(@"%@",CSVstring);

}

  CSVPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.csv", @"CSV_FormatedTable"]];

  //add our file to the path
  [fileManager createFileAtPath:CSVPath contents:[CSVstring dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

  NSData *rolesCSVData =[NSData dataWithContentsOfFile:CSVPath];
  [mailpage addAttachmentData:rolesCSVData mimeType:@"text/csv" fileName:@"CSV_FormatedTable.csv"];

DataBase File:

enter image description here

Required Format:

enter image description here

My Out Put CSV file:

enter image description here

Could any one suggest me how to do this


Solution

  • There is no need for using multiple \ts and ,s at the same time.

    You can simplify your format like this:

        record = [NSString stringWithFormat:@"%@, %@, %@", [ [storedContactsArray objectAtIndex:i] objectForKey"id"] ,  [ [storedContactsArray objectAtIndex:i] objectForKey"title"],  [ [storedContactsArray objectAtIndex:i] objectForKey"Definition"]];
    

    In any case, you will see a correct alignment only if you open the resulting file in a suitable program, e.g., Excel (and also choose the correct import options). A text editor will not usually display your CSV data in a tabular format. Aside from the way your text editor displays it, the file format is fine.