CSV文件简单操作

github第三方解析代码地址:https://github.com/davedelong/CHCSVParser

以下非CHCSVParser用法,仅是我自己copy改的demo代码:

- (void) exportImpl

{    

//    NSArray* documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

//    NSString* documentsDir = [documentPaths objectAtIndex:0];

    NSString* csvPath = [NSTemporaryDirectory() stringByAppendingPathComponent: @"export.csv"];

    NSLog(@"%@" , NSTemporaryDirectory());

    

    // TODO: mutex lock?

    [self exportCsv: csvPath];

    

    // mail is graphical and must be run on UI thread

    [self performSelectorOnMainThread: @selector(mail:) withObject: csvPath waitUntilDone: NO];

}

 

- (void) mail: (NSString*) filePath

{

    

    if ([MFMailComposeViewControllercanSendMail]) {

        // TODO: autorelease pool needed ?

        NSData* database = [NSData dataWithContentsOfFile: filePath];

        

        if (database != nil) {

            MFMailComposeViewController* picker = [[MFMailComposeViewControlleralloc] init];

            picker.mailComposeDelegate = self;

            [picker setSubject:[NSStringstringWithFormat: @"%@ %@", [[UIDevicecurrentDevice] model], [filePath lastPathComponent]]];

            [picker setToRecipients:@[@"xx@xx.com"]];

            

            NSString* filename = [filePath lastPathComponent];

            [picker addAttachmentData: database mimeType:@"application/octet-stream" fileName: filename];

            NSString* emailBody = @"Attached is the SQLite data from my iOS device.";

            [picker setMessageBody:emailBody isHTML:YES];

            

            [self presentViewController:picker animated:YEScompletion:^{

                

            }];

        }

    }

}

 

 

-(void) exportCsv: (NSString*) filename

{

    [self createTempFile: filename];

    NSOutputStream* output = [[NSOutputStream alloc] initToFileAtPath: filename append: YES];

    [output open];

    

    if (![output hasSpaceAvailable]) {

        NSLog(@"No space available in %@", filename);

        // TODO: UIAlertView?

    } else {

        

        NSString* headerStr = @"Source,Time,Latitude,Longitude,Accuracy\n";

        NSData *headerData = [headerStr dataUsingEncoding:NSUTF8StringEncoding];

        const void *headerBytes = [headerData bytes];

        int headerLength = [headerData length];

        uint8_t *headerBuf = (uint8_t*)headerBytes;

        NSInteger result = [output write: headerBuf maxLength: headerLength];

        if (result <= 0) {

            NSLog(@"1,exportCsv encountered error=%d from header write", result);

        }

        

        NSString* line1 = [[NSString alloc] initWithFormat: @"%@,%@,%f,%f,%d\n", @"大啊" , @"ab" , 1.1 , 1.2 , 1];

        result = [output write:(uint8_t *)[[line1 dataUsingEncoding:NSUTF8StringEncoding] bytes] maxLength: [line1 lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];

        if ((result <= 0)) {

            NSLog(@"2,exportCsv write returned %d", result);

        }

        

        NSString *line2 = @"小啊,bb,2.1,2.2,2\n";

        result = [output write:(uint8_t *)[line2 UTF8String] maxLength:[line2 length]];

        if ((result <= 0)) {

            NSLog(@"2,exportCsv write returned %d", result);

        }

        [output close];

    }

    

}

 

-(void)createTempFile:(NSString*)filename {

    NSFileManager* fileSystem = [NSFileManagerdefaultManager];

    [fileSystem removeItemAtPath: filename error: nil];

    

    NSMutableDictionary* attributes = [NSMutableDictionarydictionary];

    NSNumber* permission = [NSNumber numberWithLong: 0640];

    [attributes setObject: permission forKey: NSFilePosixPermissions];

    

    if (![fileSystem createFileAtPath:filename contents: nil attributes: attributes]) {

        NSLog(@"Unable to create temp file for exporting CSV.");

        // TODO: UIAlertView?

    }

}

 

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error

{

    NSString *msg;

    

    switch (result)

    {

            case MFMailComposeResultCancelled:

            msg = @"邮件发送取消";

            break;

            case MFMailComposeResultSaved:

            msg = @"邮件保存成功";

//            [self alertWithTitle:nil msg:msg];

            break;

            case MFMailComposeResultSent:

            msg = @"邮件发送成功";

//            [self alertWithTitle:nil msg:msg];

            break;

            case MFMailComposeResultFailed:

            msg = @"邮件发送失败";

//            [self alertWithTitle:nil msg:msg];

            break;

        default:

            break;

    }

    

    [self dismissViewControllerAnimated:YEScompletion:^{

        NSLog(@" --> %@" , msg);

    }];

}

posted on 2014-02-24 17:21  离群的野兽  阅读(804)  评论(0编辑  收藏  举报

导航