简体   繁体   中英

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:

在此处输入图片说明

Required Format:

在此处输入图片说明

My Out Put CSV file:

在此处输入图片说明

Could any one suggest me how to do this

There is no need for using multiple \\t s 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, eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM