0

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
  • You have to insert "\n" at the end each four objects. So instead of using componentsJoinedByString:, try to do it manually with for loop and add the \n. Commented Jun 27, 2014 at 13:30
  • is it possible to insert a string between two objects in an array? If I want to insert a string at index 3 which is between 1 and 4....how can i do that? Commented Jun 27, 2014 at 14:55

2 Answers 2

1
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];
...
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Sultan,The above code worked well with csv . I created an xls file, with the same code....but the problem is all the data is copied into first cell of every row. The line break worked perfectly, However the cell break is not working with xls file.
A xls file is something completely different. if you want to import a csv into excel, make sure to setup the column separator correctly.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.