将数据保存到Excel或CSV文件并通过电子邮件发送

时间:2014-03-02 02:55:49

标签: ios objective-c excel csv parse-platform

我创建了一个应用程序,您可以在其中键入信息到文本字段,将该信息保存到数据库,然后从应用程序中的数据库中检索该信息。我还想出了如何创建一个excel spreadshseet并通过电子邮件发送它。

所以我的问题是:如何将我保存的信息解析并将其实现到电子表格中。我保存了文本字段并将它们检索到视图控制器中。此外,我已经想出了如何手动发送.xls文件,但我仍然需要使用保存到解析的信息自动执行该过程。

以下是我在LibXL教程的帮助下手动输入的信息。

- (IBAction)createExcel:(id)sender
{
    NSLog(@"createExcel");

    BookHandle book = xlCreateBook(); // use xlCreateXMLBook() for working with xlsx files

    SheetHandle sheet = xlBookAddSheet(book, "Sheet1", NULL);

    xlSheetWriteStr(sheet, 1, 1, "Hello World !", 0);
    xlSheetWriteNum(sheet, 4, 1, 1000, 0);
    xlSheetWriteNum(sheet, 5, 1, 2000, 0);

    FontHandle font = xlBookAddFont(book, 0);
    xlFontSetColor(font, COLOR_RED);
    xlFontSetBold(font, true);
    FormatHandle boldFormat = xlBookAddFormat(book, 0);
    xlFormatSetFont(boldFormat, font);
    xlSheetWriteFormula(sheet, 6, 1, "SUM(B5:B6)", boldFormat);

    FormatHandle dateFormat = xlBookAddFormat(book, 0);
    xlFormatSetNumFormat(dateFormat, NUMFORMAT_DATE);
    xlSheetWriteNum(sheet, 8, 1, xlBookDatePack(book, 2011, 7, 20, 0, 0, 0, 0), dateFormat);

    xlSheetSetCol(sheet, 1, 1, 12, 0, 0);

    NSString *documentPath =
    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filename = [documentPath stringByAppendingPathComponent:@"out.xls"];

    xlBookSave(book, [filename UTF8String]);

    xlBookRelease(book);

    if (![MFMailComposeViewController canSendMail]) {
        //Show alert that device cannot send email, this is because an email account     hasn't been setup.
    }

    else {

        //**EDIT HERE**
        //Use this to retrieve your recently saved file

        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filename = [documentPath stringByAppendingPathComponent:@"out.xls"];

        //**END OF EDIT**

        NSString *mimeType = @"application/vnd.ms-excel"; //This should be the MIME type for els files. May want to double check.
        NSData *fileData = [NSData dataWithContentsOfFile:filename];
        NSString *fileNameWithExtension = @"out.xls"; //This is what you want the file to be called on the email along with it's extension:

        //If you want to then delete the file:
        NSError *error;
        if (![[NSFileManager defaultManager] removeItemAtPath:filename error:&error])
            NSLog(@"ERROR REMOVING FILE: %@", [error localizedDescription]);


        //Send email
        MFMailComposeViewController *mailMessage = [[MFMailComposeViewController alloc] init];
        [mailMessage setMailComposeDelegate:self];
        [mailMessage addAttachmentData:fileData mimeType:mimeType fileName:fileNameWithExtension];
        [self presentViewController:mailMessage animated:YES completion:nil];
    }


}

0 个答案:

没有答案