How to write array data into excel file (CSV&#

2019-09-17 10:28发布

I am trying to write the array data into excel (actually it is a CSV, but it is opened in excel). I used the following code to do that:

NSMutableArray *list;
    list = [[NSMutableArray alloc] init];

NSString *string = [list componentsJoinedByString:@","];

NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"yourFileName.csv"];
[data writeToFile:appFile atomically:YES];

It works fine, but the problem is I have 20 objects in my 'list' array and all those 20 objects are written in side by side cells. What I want is to write the first 4 objects in one line and then move to the new line and again write the next 4 objects in that line till all the objects in the list array are completed.

Can anyone help me with this issue?

2条回答
Fickle 薄情
2楼-- · 2019-09-17 10:44
NSMutableArray *list = ...

NSMutableString *buffer = [NSMutableString string];

for (NSUInteger i = 0; i < list.count; i++) {
    NSString *value = list[i];

    if (i > 0) {
       if (i % 4 == 0) { //after every 4th value
          buffer.append("\n"); //end line
       }
       else {
          buffer.append(",");
       }
    }

    buffer.append(value);

    //if your values contain spaces, you should add quotes around values...
    //buffer.appendFormat(@"\"%@\"", value);
}

NSData *data = [buffer dataUsingEncoding:NSUTF8StringEncoding];
...
查看更多
Bombasti
3楼-- · 2019-09-17 11:01

To break lines in CSV just input a \r\n in the "end of the line". Be caerfull because in the mac you only need \r or \n (not really sure right now)

查看更多
登录 后发表回答