Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a CSV file?

I have data exported to excel it works fine. But I have a little question

My output is exported like this:

enter image description here

What i would like to happen is this:

enter image description here

and this is my code to export:

-(void)exportCSV {

    NSArray * data = [NSArray arrayWithObjects:entries,keys, nil];
    NSLog(@"%@",data);
    csv =[NSMutableString string];
    for (NSArray * line in data) {
        NSMutableArray * formattedLine = [NSMutableArray array];
        for ( field in line) {
            BOOL shouldQuote = NO;
            NSRange r = [field rangeOfString:@","];
            //fields that contain a , must be quoted
            if (r.location != NSNotFound) {
                shouldQuote = YES;
            }
            r = [field rangeOfString:@"\""];
            //fields that contain a " must have them escaped to "" and be quoted
            if (r.location != NSNotFound) {
                field = [field stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
                shouldQuote = YES;
            }
            if (shouldQuote == YES) {
                [formattedLine addObject:[NSString stringWithFormat:@"\"%@\"\"%@\"", entries,keys]];
            } else {
                [formattedLine addObject:field];
            }
        }

        NSString * combinedLine = [formattedLine componentsJoinedByString:@";"];
        [csv appendFormat:@"%@\n", combinedLine];

        NSLog(@"%@",csv);
    }

}
like image 229
Thymen Avatar asked Apr 16 '13 13:04

Thymen


1 Answers

Does the following do what you want?
Note that I have not considered quotation, I leave that up to you ;)
Also note that I assume that entries.count == keys.count

- (void)exportCSV {    
    NSArray *keys = @[@"T", @"R", @"RTT"];
    NSArray *entries = @[@"-329180696", @"1243918297", @"-998693494"];
    NSMutableString *csv = [[NSMutableString alloc] initWithCapacity:0];
    for (int i = 0; i < entries.count; i++) {
        [csv appendFormat:@"%@;%@\n", keys[i], entries[i]];
    }
}

Output:

T;-329180696
R;1243918297
RTT;-998693494

like image 94
HAS Avatar answered Oct 15 '22 01:10

HAS