
使用到的三方库 https://github.com/jmcnamara/libxlsxwriter
cocoapods导入
pod 'libxlsxwriter', '~> 0.8.3'
1.引入头文件
#import <xlsxwriter/xlsxwriter.h>
2.示例代码
NSArray *array=@[@{@"name":@"数学",@"time":@"2018-10-21"},@{@"name":@"语文",@"time":@"2018-10-22"}]; // 文件保存的路径 NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; NSString *filename = [documentPath stringByAppendingPathComponent:@"testDemo.xlsx"]; NSLog(@"filepath:%@",filename); lxw_workbook *workbook = workbook_new([filename UTF8String]);// 创建新xlsx文件,路径需要转成c字符串 lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);// 创建sheet [array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { NSDictionary *aDic=obj; NSString *name=aDic[@"name"]; NSString *time=aDic[@"time"]; uint32_t lxw_row_t = (uint32_t)idx; worksheet_write_string(worksheet, lxw_row_t, 0, [name UTF8String], NULL); worksheet_write_string(worksheet, lxw_row_t, 1, [time UTF8String], NULL); }]; //关闭,保存文件 workbook_close(workbook); |
3.最终结果 (生成的excel文件在filepath打印的文件路径中,finder前往文件夹即可)