在Xcode中以编程方式创建Excel电子表格

3
我正在尝试将Excel电子表格集成到iOS中,以便最终以.xls或.csv格式通过电子邮件发送。我找到了一篇教程,我认为这正是我想要的,但我还不知道如何在电子邮件中发送它。我熟悉在电子邮件中发送文本,但不太熟悉发送文件。
以下是教程链接 - http://xcodetipss.blogspot.com/2013/11/create-excelxls-file-programatically-in.html 以下是教程代码:
 1. Download Library from the url : Libxl Download and then add LibXL.framework to your xcode project

 2. Down your deployment target to ios6.0

 3. In Other linker Flag - set "-lstdc++"

 4. Add Framework -  “libc++.dylib”

 5. Add in your view controller - 
 #include "LibXL/libxl.h”

 6. Create xls file from the below code  and save to document directory.

 BookHandle book = xlCreateBook(); // use xlCreateXMLBook() for working with xlsx files                 SheetHandle sheet = xlBookAddSheet(book, "Sheet1", NULL);    
 FontHandle font = xlBookAddFont(book, 0);   
 xlFontSetColor(font, COLOR_RED);    
 xlFontSetBold(font, true);    
 FormatHandle boldFormat = xlBookAddFormat(book, 0);    
 xlFormatSetFont(boldFormat, font);     
 xlSheetWriteStr(sheet, 2, 1, "Title", boldFormat);    
 xlSheetWriteStr(sheet, 2, 2, "First name", boldFormat);    
 xlSheetWriteStr(sheet, 2, 3, "Last name", boldFormat);    
 xlSheetWriteStr(sheet, 2, 4, "Nationality", boldFormat);    
 xlSheetWriteStr(sheet, 2, 5, "Address", boldFormat);    
 xlSheetWriteStr(sheet, 2, 6, "P.O.Box", boldFormat);    
 xlSheetWriteStr(sheet, 2, 7, "City", boldFormat);    
 xlSheetWriteStr(sheet, 2, 8, "Country", boldFormat);    
 xlSheetWriteStr(sheet, 2, 9, "Phone", boldFormat);    
 xlSheetWriteStr(sheet, 2, 10, "Email", boldFormat);    
 xlSheetWriteStr(sheet, 2, 11, "Birth Date", boldFormat);    
 xlSheetWriteStr(sheet, 2, 12, "Wedding Date", boldFormat);        
 NSMutableArray *dataArray = [[NSMutableArray alloc]init];    
 dataArray = [Database executeQuery:@"select * from user"];    
 for (int i=0; i<[dataArray count]; i++) {        
 NSDictionary *dict = [dataArray objectAtIndex:i];        
 const char *converted_back = [[dict objectForKey:@"title"] UTF8String];        
 const char *converted_back1 = [[dict objectForKey:@"firstname"] UTF8String];        
 const char *converted_back2 = [[dict objectForKey:@"lastname"] UTF8String];        
 const char *converted_back3 = [[dict objectForKey:@"nationality"] UTF8String];        
 const char *converted_back4 = [[dict objectForKey:@"address"] UTF8String];        
 const char *converted_back5 = [[dict objectForKey:@"pobox"] UTF8String];        
 const char *converted_back6 = [[dict objectForKey:@"city"] UTF8String];        
 const char *converted_back7 = [[dict objectForKey:@"country"] UTF8String];        
 const char *converted_back8 = [[dict objectForKey:@"phone"] UTF8String];        
 const char *converted_back9 = [[dict objectForKey:@"email"] UTF8String];        
 const char *converted_back10 = [[dict objectForKey:@"birthdate"] UTF8String];        
 const char *converted_back11 = [[dict objectForKey:@"weddingdate"] UTF8String];

 xlSheetWriteStr(sheet, i+3, 1, converted_back, 0);        
 xlSheetWriteStr(sheet, i+3, 2, converted_back1, 0);        
 xlSheetWriteStr(sheet, i+3, 3, converted_back2, 0);        
 xlSheetWriteStr(sheet, i+3, 4, converted_back3, 0);        
 xlSheetWriteStr(sheet, i+3, 5, converted_back4, 0);        
 xlSheetWriteStr(sheet, i+3, 6, converted_back5, 0);        
 xlSheetWriteStr(sheet, i+3, 7, converted_back6, 0);        
 xlSheetWriteStr(sheet, i+3, 8, converted_back7, 0);        
 xlSheetWriteStr(sheet, i+3, 9, converted_back8, 0);        
 xlSheetWriteStr(sheet, i+3, 10, converted_back9, 0);        
 xlSheetWriteStr(sheet, i+3, 11, converted_back10, 0);        
 xlSheetWriteStr(sheet, i+3, 12, converted_back11, 0);    
 }     

 NSString *documentPath =    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];    
 NSString *filename = [documentPath stringByAppendingPathComponent:@"Cartier.xls"];          xlBookSave(book, [filename UTF8String]);   
 xlBookRelease(book);

所以我的问题是 - 如何在Xcode中实现这一点,以便可以通过电子邮件发送。

提前致谢。

这是我的.h文件

//
//  DataViewController.h
//  libxl-example
//
//  Created by dmytro on 12/25/12.
//  Copyright (c) 2012 xlware. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@interface DataViewController : UIViewController <MFMailComposeViewControllerDelegate>

@property (strong, nonatomic) IBOutlet UILabel *dataLabel;
@property (strong, nonatomic) id dataObject;

- (IBAction)createExcel:(id)sender;



@end

这是我的 .m 文件

//
//  DataViewController.m
//  libxl-example
//
//  Created by dmytro on 12/25/12.
//  Copyright (c) 2012 xlware. All rights reserved.
//

#import "DataViewController.h"

#include "LibXL/libxl.h"

@interface DataViewController ()


@end
@implementation DataViewController

- (void)dealloc
{
    [_dataLabel release];
    [_dataObject release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.dataLabel.text = [self.dataObject description];
}

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

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

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

    xlSheetWriteStr(sheet, 2, 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:@"Cartier.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 = @"Cartier.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];
    }


}


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

    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued.");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved: you saved the email message in the drafts folder.");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send.");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed: the email message was not saved or queued, possibly due to an error.");
            break;
        default:
            NSLog(@"Mail not sent.");
            break;
    }

    [controller dismissViewControllerAnimated:YES completion:nil];
}

@end
1个回答

3

一旦您将其保存到文档目录中,将其发送到电子邮件就相当简单:

 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:@"Cartier.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 = @"Cartier.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];
 }

邮件委托方法如下:

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

    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued.");
        break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved: you saved the email message in the drafts folder.");
        break;
        case MFMailComposeResultSent:
            NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send.");
        break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed: the email message was not saved or queued, possibly due to an error.");
        break;
        default:
            NSLog(@"Mail not sent.");
        break;
    }

    [controller dismissViewControllerAnimated:YES completion:nil];
}

*编辑 -- *

您需要包括MessageUI框架(Build Phases,Link Binary with Libraries),然后在您的.h文件顶部添加以下内容:

#import <MessageUI/MessageUI.h>

然后订阅该委托:

@interface YOURCONTROLLER : UIViewController <MFMailComposeViewControllerDelegate>

你会如何将这个实现到我已有的代码中? - user3229614
当我将代码添加到正在工作的项目中时,它会显示MFMail是未声明的标识符。您知道如何解决这个问题吗?任何帮助都将不胜感激。 - user3229614
我还剩下唯一的一个错误,就是当我添加以下这行代码时:
  • (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
我会得到一个错误:使用了未声明的标识符“mailComposeController”。我该如何解决这个问题?
- user3229614
你的电子邮件是什么?我想给你发送一张错误截图,但是 Stack Overflow 不允许我这样做。 - user3229614
我不需要电子邮件。你是否将框架添加到构建设置中了? - CW0007007
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接