首页 > 解决方案 > Objective-C - 如何打开 .csv 文件?

问题描述

我是编程新手。不幸的是,我没有 C 或 Objective-C 的经验。我的问题很简单。

如何使用 MS Excel 从打开的面板打开 .csv 文件?如何将 .csv 文件导出到数据库中?

感谢您的时间和帮助。

#import "AppDelegate.h"

@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end
@implementation AppDelegate
- (IBAction)Browse:(id)sender {
    {
     NSOpenPanel *openPanel = [NSOpenPanel openPanel];

     [openPanel setAllowedFileTypes:[NSArray arrayWithObjects:@"csv", nil]];
        // Permet seulement d'ouvrir un fichier .csv
     [openPanel setAllowsMultipleSelection:YES];
     [openPanel setDirectoryURL:[NSURL URLWithString:[NSHomeDirectory() stringByAppendingPathComponent:@"Bureau"]]];
        // Ouvre le répertoire Bureau en automatique

        if([openPanel runModal] == NSModalResponseOK)
            [[NSWorkspace sharedWorkspace] openFile: 
            withApplication:@"Microsoft Excel"];
            NSLog(@"Fichier ouvert : %@", [openPanel URL]);
        }
    }
@end

标签: objective-cxcodemacos

解决方案


请试试这个片段。请记住,您可能需要将每一列作为一个行值来处理。

NSMutableArray *colA = [NSMutableArray array];
NSMutableArray *colB = [NSMutableArray array];

NSString* fileContents = [NSString stringWithContentsOfURL:@"microsoft-excel.csv"];

NSArray* rows = [fileContents componentsSeparatedByString:@"\n"];

for (NSString *row in rows){
     NSArray* columns = [row componentsSeparatedByString:@","];
     [colA addObject:columns[0]];
     [colB addObject:columns[1]];
}

推荐阅读