草庐IT

ios - 在 xcode 中以编程方式创建 excel 电子表格

coder 2024-01-19 原文

我正在尝试将 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

最佳答案

将其保存到文档目录后,通过电子邮件发送它就相当简单了:

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

然后电子邮件委托(delegate)方法是:

- (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>

然后订阅委托(delegate):

@interface YOURCONTROLLER : UIViewController <MFMailComposeViewControllerDelegate>

关于ios - 在 xcode 中以编程方式创建 excel 电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21358772/

有关ios - 在 xcode 中以编程方式创建 excel 电子表格的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  6. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  7. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  8. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  9. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  10. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

随机推荐