UIDocumentInteractionControllerDelegate
/// 调用safari分享功能将文件分享出去 实现代理 Delegate,查看不了 需要去App Store 下载 WPS office APP
@property (nonatomic, strong) UIDocumentInteractionController *documentIc;
- (void)createXLSFile {
// 创建存放XLS文件数据的数组
NSMutableArray *xlsDataMuArr = [[NSMutableArray alloc] init];
// 第一行内容
[xlsDataMuArr addObject:@"Time"];
[xlsDataMuArr addObject:@"Address"];
[xlsDataMuArr addObject:@"Person"];
[xlsDataMuArr addObject:@"Reason"];
[xlsDataMuArr addObject:@"Process"];
[xlsDataMuArr addObject:@"Result"];
// 10行数据
for (int i = 0; i < 10; i ++) {
[xlsDataMuArr addObject:@"下班时间"];
[xlsDataMuArr addObject:@"大连"];
[xlsDataMuArr addObject:@"弄啪波勒"];
[xlsDataMuArr addObject:@"哦"];
[xlsDataMuArr addObject:@"很酷"];
[xlsDataMuArr addObject:@"又很帅气"];
}
// 把数组拼接成字符串,连接符是 \t(功能同键盘上的tab键)
NSString *fileContent = [xlsDataMuArr componentsJoinedByString:@"\t"];
// 字符串转换为可变字符串,方便改变某些字符
NSMutableString *muStr = [fileContent mutableCopy];
// 新建一个可变数组,存储每行最后一个\t的下标(以便改为\n)
NSMutableArray *subMuArr = [NSMutableArray array];
for (int i = 0; i < muStr.length; i ++) {
NSRange range = [muStr rangeOfString:@"\t" options:NSBackwardsSearch range:NSMakeRange(i, 1)];
if (range.length == 1) {
[subMuArr addObject:@(range.location)];
}
}
// 替换末尾\t
for (NSUInteger i = 0; i < subMuArr.count; i ++) {
#warning 下面的6是列数,根据需求修改
if ( i > 0 && (i%6 == 0) ) {
[muStr replaceCharactersInRange:NSMakeRange([[subMuArr objectAtIndex:i-1] intValue], 1) withString:@"\n"];
}
}
// 文件管理器
NSFileManager *fileManager = [[NSFileManager alloc]init];
//使用UTF16才能显示汉字;如果显示为#######是因为格子宽度不够,拉开即可
NSData *fileData = [muStr dataUsingEncoding:NSUTF16StringEncoding];
// 文件路径
NSString *path = NSHomeDirectory();
NSString *filePath = [path stringByAppendingPathComponent:@"/Documents/export.xlsx"];
XPFLog(@"文件路径:\n%@",filePath);
// 生成xls文件
[fileManager createFileAtPath:filePath contents:fileData attributes:nil];
// 调用safari分享功能将文件分享出去
UIDocumentInteractionController *documentIc = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
// 记得要强引用UIDocumentInteractionController,否则控制器释放后再次点击分享程序会崩溃
self.documentIc = documentIc;
// 如果需要其他safari分享的更多交互,可以设置代理
documentIc.delegate = self;
// 设置分享显示的矩形框
CGRect rect = CGRectMake(0, 0, 300, 300);
[documentIc presentOpenInMenuFromRect:rect inView:self.view animated:YES];
[documentIc presentPreviewAnimated:YES];
}