Frage

In my app I'm creating a .plist file, but I need to use the data I stored in this .plist in an Excel table. I need a way to get a csv form this plist. I tried to search on the web but I found only converter that allow to create a plist from a csv. I guess there's a way to generate a csv file directly from my iPad app. Does anyone know a way to do that?

UPDATE:

+ (void)saveFileFromArray:(NSMutableArray *)promoArray {
    NSMutableString *target = [@"Nome,Cognome,E-mail,Data di nascita,Indirizzo,Città,Cap,Telefono\n" mutableCopy];

    for (NSDictionary *dict in promoArray) {
        [target appendFormat:@"%@,%@,%@,%@,%@,%@,%@,%@\n",dict[@"name"],dict[@"surname"],dict[@"email"],dict[@"birthdate"],dict[@"address"],dict[@"city"],dict[@"zip"],dict[@"phone"]];
    }
    NSError *error = nil;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"profiles.csv"];

    NSURL *url = [NSURL URLWithString:fileName];

    BOOL success = [target writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];

    if (!success) {
        NSLog(@"Errore: %@", error.localizedDescription);
    }
}
War es hilfreich?

Lösung

Iterate through the array, and write the parts you wish to, to a string.

A string with commas in will help considerably. Carriages returns are good too.

When the string is done. Write it to a file.

NSMutableString *target = [@"head1,head2,head3\n" mutableCopy];

for (NSDictionary *dict in array) {

    [target appendFormat:@"%@,%@,%@\n",dict[@"thing"],dict[@"otherthing"],dict[@"lemming"]];

}

NSError *error = NULL;

BOOL success = [target writeToURL:somewhere atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (!success) {
    NSLog(@"oh no! - %@",error.localizedDescription);
}

The snippet assumes you have an array of NSDictionary but in case its something else the principle is the same.

For each object print out a comma separated string and terminate with a CR.

Things you will have to guard against in real world data are

  • descriptions with a comma in already.
  • descriptions with a CR in already.

Andere Tipps

Just use a framework that has already been developed and tested. I use https://github.com/davedelong/CHCSVParser which works fine.

Occasionally, I have to add a feature or two, but given that it is open source it is not a big deal.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top