如何写阵列数据成Objective C的Excel文件(CSV) [英] How to write array data into excel file (CSV) in objective c
问题描述
我想数组数据写入到Excel(实际上它是一个CSV,但它是在Excel中打开)。我用下面的code要做到这一点:
的NSMutableArray *名单;
名单= [[NSMutableArray里的alloc]初始化];* NSString的字符串= [列表componentsJoinedByString:@];NSData的*数据= [串dataUsingEncoding:NSUTF8StringEncoding];
NSArray的*路径= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
的NSString * documentsDirectory = [路径objectAtIndex:0];
* NSString的appFile = [documentsDirectory stringByAppendingPathComponent:@yourFileName.csv];
[数据将writeToFile:appFile原子:YES];
它工作正常,但问题是我在我的名单阵列20个对象和所有20个对象被并排细胞写在身边。我要的是写第4物体在同一行,然后移动到新的生产线,并再次写入下一个4个对象在该行,直到列表数组中的所有对象都完成了。
谁能帮我这个问题?
的NSMutableArray *列表= ...*的NSMutableString缓冲= [字符串的NSMutableString];对于(NSUInteger我= 0; I< list.count;我++){
* NSString的值=列表[我] 如果(I 0){
如果(I%4 == 0){//以后每4个值
buffer.append(\\ n); //端线
}
其他{
buffer.append(,);
}
} buffer.append(值); //如果你的价值观包含空格,应添加引号值...
//buffer.appendFormat(@\\%@ \\,值);
}NSData的*数据= [缓冲dataUsingEncoding:NSUTF8StringEncoding];
...
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?
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];
...
这篇关于如何写阵列数据成Objective C的Excel文件(CSV)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!