我有數據導出到Excel它工作正常。 但我有一個小問題如何生成CSV文件?
我的輸出導出這樣的:
什麼,我想發生是這樣的:
,這是我的代碼出口:
-(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);
}
}
它看起來像'data'中的第一行是列標題,後續行包含數據。既然你一次只處理一行內容,你就能得到你所期望的。要獲得轉置,您需要將所有數據讀入數組的列中,然後將其讀出(反之亦然)。或者,第一次打開Excel文件後,請執行「選擇全切 - 粘貼特殊轉置」。後者會更容易... – Floris
這個問題與Excel無關。這是一個「生成CSV」的問題。 – rmaddy