简体   繁体   中英

Objective-C - How to open a .csv file?

I am all new on programming. Unfortunately I have no experience in C or Objective-C. My question is quite simple.

How could I open with MS Excel a .csv file from the open panel ? How could I export a .csv file into a database ?

Thank you for your time and your help.

#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

Please try this snippet. Remember that you may need to handle each column as a row value.

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]];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM