Export SQLite data to Excel in iOS programmatically(OC)
{
// in my full code, I start a UIActivityIndicator spinning and show a
// message that the app is "Exporting ..."
[self performSelectorInBackground: @selector(exportImpl) withObject: nil];
}
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSArray* documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSSystemDomainMask, YES);
NSString* documentsDir = [documentPaths objectAtIndex:0];
NSString* csvPath = [documentsDir stringByAppendingPathComponent: @"export.csv"];
// TODO: mutex lock?
[sqliteDb exportCsv: csvPath];
[pool release];
// mail is graphical and must be run on UI thread
[self performSelectorOnMainThread: @selector(mail:) withObject: csvPath waitUntilDone: NO];
}
- (void) mail: (NSString*) filePath
{
// here I stop animating the UIActivityIndicator
// http://howtomakeiphoneapps.com/home/2009/7/14/how-to-make-your-iphone-app-send-email-with-attachments.html
BOOL success = NO;
if ([MFMailComposeViewController canSendMail]) {
// TODO: autorelease pool needed ?
NSData* database = [NSData dataWithContentsOfFile: filePath];
if (database != nil) {
MFMailComposeViewController* picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:[NSString stringWithFormat: @"%@ %@", [[UIDevice currentDevice] model], [filePath lastPathComponent]]];
NSString* filename = [filePath lastPathComponent];
[picker addAttachmentData: database mimeType:@"application/octet-stream" fileName: filename];
NSString* emailBody = @"Attached is the SQLite data from my iOS device.";
[picker setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker animated:YES];
success = YES;
[picker release];
}
}
if (!success) {
UIAlertView* warning = [[UIAlertView alloc] initWithTitle: @"Error"
message: @"Unable to send attachment!"
delegate: self
cancelButtonTitle: @"Ok"
otherButtonTitles: nil];
[warning show];
[warning release];
}
}
{
// We record this filename, because the app deletes it on exit
self.tempFile = filename;
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// Setup the database object
sqlite3* database;
// Open the database from the users filessytem
if (sqlite3_open([self.databasePath UTF8String], &database) == SQLITE_OK)
{
[self createTempFile: filename];
NSOutputStream* output = [[NSOutputStream alloc] initToFileAtPath: filename append: YES];
[output open];
if (![output hasSpaceAvailable]) {
NSLog(@"No space available in %@", filename);
// TODO: UIAlertView?
} else {
NSString* header = @"Source,Time,Latitude,Longitude,Accuracy\n";
NSInteger result = [output write: [header UTF8String] maxLength: [header length]];
if (result <= 0) {
NSLog(@"exportCsv encountered error=%d from header write", result);
}
BOOL errorLogged = NO;
NSString* sqlStatement = @"select timestamp,latitude,longitude,horizontalAccuracy from my_sqlite_table";
// Setup the SQL Statement and compile it for faster access
sqlite3_stmt* compiledStatement;
if (sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
{
// Loop through the results and write them to the CSV file
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSInteger secondsSinceReferenceDate = (NSInteger)sqlite3_column_double(compiledStatement, 0);
float lat = (float)sqlite3_column_double(compiledStatement, 1);
float lon = (float)sqlite3_column_double(compiledStatement, 2);
float accuracy = (float)sqlite3_column_double(compiledStatement, 3);
if (lat != 0 && lon != 0) {
NSDate* timestamp = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: secondsSinceReferenceDate];
NSString* line = [[NSString alloc] initWithFormat: @"%@,%@,%f,%f,%d\n",
table, [dateFormatter stringFromDate: timestamp], lat, lon, (NSInteger)accuracy];
result = [output write: [line UTF8String] maxLength: [line length]];
if (!errorLogged && (result <= 0)) {
NSLog(@"exportCsv write returned %d", result);
errorLogged = YES;
}
[line release];
[timestamp release];
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
}
}
[output close];
[output release];
}
sqlite3_close(database);
[pool release];
}
-(void) createTempFile: (NSString*) filename {
NSFileManager* fileSystem = [NSFileManager defaultManager];
[fileSystem removeItemAtPath: filename error: nil];
NSMutableDictionary* attributes = [[NSMutableDictionary alloc] init];
NSNumber* permission = [NSNumber numberWithLong: 0640];
[attributes setObject: permission forKey: NSFilePosixPermissions];
if (![fileSystem createFileAtPath: filename contents: nil attributes: attributes]) {
NSLog(@"Unable to create temp file for exporting CSV.");
// TODO: UIAlertView?
}
[attributes release];
}
Export SQLite data to Excel in iOS programmatically(OC)的更多相关文章
- Export GridView Data to Excel. 从GridView导出数据到Excel的奇怪问题解析
GridView导出函数内容如下 string attachment = "attachment; filename=Contacts.xls"; Respo ...
- NetSuite SuiteScript 2.0 export data to Excel file(xls)
In NetSuite SuiteScript, We usually do/implement export data to CSV, that's straight forward: Collec ...
- Insert data from excel to database
USE ESPA Truncate table dbo.Interface_Customer --Delete the table data but retain the structure exec ...
- Tutorial: Analyzing sales data from Excel and an OData feed
With Power BI Desktop, you can connect to all sorts of different data sources, then combine and shap ...
- Use JavaScript to Export Your Data as CSV
原文: http://halistechnology.com/2015/05/28/use-javascript-to-export-your-data-as-csv/ --------------- ...
- iOS开发OC基础:Xcode中常见英文总结,OC常见英文错误
在开发的过程中难免会遇到很多的错误,可是当看到系统给出的英文时,又不知道是什么意思.所以这篇文章总结了Xcode中常见的一些英文单词及词组,可以帮助初学的人快速了解给出的提示.多练习,就肯定能基本掌握 ...
- 转载 iOS js oc相互调用(JavaScriptCore) --iOS调用js
iOS js oc相互调用(JavaScriptCore) 从iOS7开始 苹果公布了JavaScriptCore.framework 它使得JS与OC的交互更加方便了. 下面我们就简单了解一下这 ...
- C# Note38: Export data into Excel
Microsoft.Office.Interop.Excel You have to have Excel installed. Add a reference to your project to ...
- ios创建的sqlite数据库文件如何从ios模拟器中导出
为了验证数据库的结构,有的时候需要使用一些管理工具来直接查看sqlite数据库的内容,在windows下有sqlite3的专用工具下载,而在ios下也可以使用火狐浏览器的插件sqlitemanager ...
随机推荐
- 基于神念TGAM的脑波小车(1)
作者声明:此博客是作者的毕设心得,拿来分享. 拿到模块,在网上查了一圈,发现基本没什么有用的资料,有也是一些废话,经过我几个月的攻克,现在已初步搞定,分享给大家. 废话不多说,直接步入正题. 这是通过 ...
- 开源一个最近写的spring与mongodb结合的demo(spring-mongodb-demo)
由于工作需要,给同事们分享了一下mongodb的使用,其中主要就是做了一个spring-data+mongodb的小例子,本着分享的精神,就上传到了github.com上,有需要的同学请移步githu ...
- Linux内核分析— —计算机是如何工作的(20135213林涵锦)
实验部分 (以下命令为实验楼64位Linux虚拟机环境下适用,32位Linux环境可能会稍有不同) 使用 gcc –S –o main.s main.c -m32 命令编译成汇编代码, int g(i ...
- java入门--4111:判断游戏胜者-Who Is the Winner
基础的题目 学习了StringBuilder, 通过delete来清空它 学了Map的简单用法 import java.util.*; public class Main { public stati ...
- nodeJs上传附件
两种方案: 这两种方案传参还是有区别额 在nodeJs中上传附件调用了 multer 的中间件,采用这个中间件来上传 首先是表单(前端部分): <!DOCTYPE html> <ht ...
- 转 kvm、qemu-kvm、ibvirt及openstack,之间的关系
KVM是最底层的hypervisor,它是用来模拟CPU的运行,它缺少了对network和周边I/O的支持,所以我们是没法直接用它的. QEMU-KVM就是一个完整的模拟器,它是构建基于KVM上面的, ...
- C++ STL 的底层数据结构实现
C++ STL 的实现: 1.vector 底层数据结构为数组 ,支持快速随机访问 2.list 底层数据结构为双向链表,支持快速增删 3.deque ...
- luogu2678 [NOIp2015]跳石头 (二分答案+贪心)
先二分出一个x,我们要算使最近的跳跃距离>=x的最少移除数量是否<=M就可以了 然后就别dp了...贪心就完事了...我肯定能不移就不移比较好... #include<bits/st ...
- 【uoj7】 NOI2014—购票
http://uoj.ac/problem/7 (题目链接) 题意 给出一棵有根树,每次从一个节点出发可以买票到达它的一定范围内的祖先.问对于每一个点,到达根的最小花费是多少. Solution 右转 ...
- 数组初始化 memset fill
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #in ...