3

我正在使用以下代码在我的 iOS 应用程序上创建一个 *.xls 文件。一切进展顺利。我可以用 Microsoft Excel 打开它,但如果我想用 Apple Numbers 打开它,它就不起作用。

- (void)exportToExcel
{
    NSManagedObjectContext *context = [self managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    NSError *error;
    NSString *header = @"<?xml version=\"1.0\"?>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\nxmlns:o=\"urn:schemas-microsoft-com:office:office\"\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\nxmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\nxmlns:html=\"http://www.w3.org/TR/REC-html40\">\n<Worksheet ss:Name=\"Sheet1\">\n<Table ss:ExpandedColumnCount=\"";
    NSString *columncount = @"\" ss:ExpandedRowCount=\"";
    NSString *rowcount = @"\" x:FullColumns=\"1\"x:FullRows=\"1\">\n";

    NSString *rowStart = @"<Row>\n";
    NSString *rowEnde = @"\n</Row>\n";

    NSString *stringStart = @"<Cell><Data ss:Type=\"String\">";
    NSString *stringEnde = @"</Data></Cell>";

    NSString *numberStart = @"<Cell><Data ss:Type=\"Number\">";
    NSString *numberEnde = @"</Data></Cell>";

    NSString *footer = @"</Table>\n</Worksheet>\n</Workbook>";

    NSString *xlsstring = @"";

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Form" inManagedObjectContext:context];

    [request setEntity:entity];

    NSArray *arr = [context executeFetchRequest:request error:&error];

    int numberOfRows = 1;
    int numberOfCols = 2;

    for (Form *form in arr) {
        numberOfRows = numberOfRows + 1;
    }

    xlsstring = [NSString stringWithFormat:@"%@%i%@%i%@", header, numberOfCols, columncount, numberOfRows, rowcount];
    xlsstring = [xlsstring stringByAppendingFormat:@"%@%@Patient number%@%@Name%@%@", rowStart, stringStart, stringEnde, stringStart, stringEnde, rowEnde];

    for (Form *form in arr) {
        xlsstring = [xlsstring stringByAppendingFormat:@"%@%@%@%@%@%@%@%@", rowStart, numberStart, form.pnumber, numberEnde, stringStart, form.name, stringEnde, rowEnde];
    }
    xlsstring = [xlsstring stringByAppendingFormat:@"%@", footer];

    [xlsstring writeToFile:@"/Users/***/Desktop/form.xls" atomically:YES encoding:NSISOLatin1StringEncoding error:nil];
}

有谁知道为什么会这样,甚至有解决这个错误的方法?

4

1 回答 1

3

Numbers 不会导入 Excel XML 格式。(请参见此处。)它将导入 Excel 原生格式,但编写这将不是一件容易的事。

您能否让您的应用程序同时选择 Excel XML(适用于 Excel 用户)和 CSV(适用于 Numbers 用户)?

于 2012-05-24T11:44:15.417 回答