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

时间:2014-03-02 22:38:43

标签: ios excel parse-platform

看看我创建的图片,以帮助您更好地理解我提出的问题。

enter image description here 另外,这是教程,我在那里保存了要解析的文本字段:

http://www.appcoda.com/ios-programming-save-data-parse-cloud-tutorial/

以下是我在excel信息中获得所有ios的网站:

http:// libxl.com/download.html

它可以保存数据以进行解析并显示它。此外,我可以手动创建.xls(excel)文件,并通过电子邮件将其发送给某人。我现在需要做的就是使用解析后的数据填充.xls文件。

这是我的.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>
#import <Parse/Parse.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"
#import "RecipeBookViewController.h"
#import "RecipeDetailViewController.h"
#import "Recipe.h"

@interface RecipeBookViewController ()

@end

@implementation RecipeBookViewController {

}

- (id)initWithCoder:(NSCoder *)aCoder
{
    self = [super initWithCoder:aCoder];
    if (self) {
        // Custom the table

        // The className to query on
        self.parseClassName = @"Recipe";

        // The key of the PFObject to display in the label of the default cell style
        self.textKey = @"name";

        // Whether the built-in pull-to-refresh is enabled
        self.pullToRefreshEnabled = YES;

        // Whether the built-in pagination is enabled
        self.paginationEnabled = NO;

        // The number of objects to show per page
        //self.objectsPerPage = 10;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshTable:)
                                                 name:@"refreshTable"
                                               object:nil];
}

- (void)refreshTable:(NSNotification *) notification
{
    // Reload the recipes
    [self loadObjects];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshTable" object:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (PFQuery *)queryForTable
{
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];

    // If no objects are loaded in memory, we look to the cache first to fill the table
    // and then subsequently do a query against the network.
    /*    if ([self.objects count] == 0) {
     query.cachePolicy = kPFCachePolicyCacheThenNetwork;
     }*/

    //    [query orderByAscending:@"name"];

    return query;
}



// Override to customize the look of a cell representing an object. The default is to display
// a UITableViewCellStyleDefault style cell with the label being the first key in the object.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
    static NSString *simpleTableIdentifier = @"RecipeCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    // Configure the cell
    PFFile *thumbnail = [object objectForKey:@"imageFile"];
    PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
    thumbnailImageView.image = [UIImage imageNamed:@"placeholder.jpg"];
    thumbnailImageView.file = thumbnail;
    [thumbnailImageView loadInBackground];

    UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
    nameLabel.text = [object objectForKey:@"name"];

    UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
    prepTimeLabel.text = [object objectForKey:@"prepTime"];

    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Remove the row from data model
    PFObject *object = [self.objects objectAtIndex:indexPath.row];
    [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        [self refreshTable:nil];
    }];
}

- (void) objectsDidLoad:(NSError *)error
{
    [super objectsDidLoad:error];

    NSLog(@"error: %@", [error localizedDescription]);
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        RecipeDetailViewController *destViewController = segue.destinationViewController;

        PFObject *object = [self.objects objectAtIndex:indexPath.row];
        Recipe *recipe = [[Recipe alloc] init];
        recipe.name = [object objectForKey:@"name"];
        recipe.imageFile = [object objectForKey:@"imageFile"];
        recipe.prepTime = [object objectForKey:@"prepTime"];
        recipe.ingredients = [object objectForKey:@"ingredients"];
        destViewController.recipe = recipe;

    }
}


@end
@interface DataViewController ()
@end
@implementation DataViewController

- (void)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, 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];
    }


}


- (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 个答案:

答案 0 :(得分:0)

在// EDIT HERE 下添加代码,使用PFQuery从Parse.com检索数据。请按照此https://parse.com/docs/ios_guide#objects-retrieving/iOS进行修改以适合您的数据结构。

如果您不确定数据结构。请登录Parse并导航到您应用的数据浏览器。它应该看起来像https://parse.com/apps/YOUR_APP_NAME/collections。然后单击该字段并找出JSON数据。 PFQuery将为您提供NSDictionary。使用NSString键查找NSDictionary以检索您喜欢的数据。