Reading data from .xls/.csv files into iOS - ios

I'm new to iOS and am trying to read the contents of a spreadsheet into an iOS array.
The spreadsheet that I'm using is a simple 3 x 2 array of numbers for the first column and text for the second. I've tried reading it in with & without column headers, in .xls, .xlsx, . cdv, .txt (unicode and delimited) but without success. The file is called "funds", and the code I'm using is:
NSData *databuffer;
NSFileHandle * file;
NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)[0];
NSString *fileDir = [docDir stringByAppendingPathComponent:#"funds.xls"];
file = [NSFileHandle fileHandleForReadingAtPath:fileDir];
if (file == nil) NSLog (#"Failed to open file");
[file seekTOOffset: 10];
databuffer = [file readDataOfLength: 5];
[file closeFile];
It finds the directory of the file but gives up at [NSFileHandle fileHandleForReadingAtPath:fileDir].
What should I be doing? I need help with confirming what file type I should use as the source, and how to read it into an array.
When this has been solved, I'm likely to need to read in large amount of data, several columns, 4k rows, a mixture of text & non-integer numbers.
Is there a format or method I should be using when the volume of data is getting to that size?

Be sure to export the data from Excel in CSV format.
It's easy to use NSFileManager to access the file:
NSString *pathName = ...; /// fill in the file's pathname
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:pathName]) {
// read the file contents, see below
}
For small files, you could just say:
NSString *lines = [NSString stringWithContentsOfFile:filePath];
and then proceed to split the string into lines, and process each line.
For large files, better have a look at some more sophisticated techniques, like in Objective-C: Reading a file line by line.
As for parsing the CSV lines, use the NSString method componentsSeparatedByString to tokenize each line, something like:
NSArray *fields = [line componentsSeparatedByString:#","];
Actually, that's also what you would use to split the file contents you read into individual lines. Just pay attention to the line feeds (CR LF or LF). You will find something in how to split a string with newlines.

There is a very popular CocoaPod / Github project that both will write and parse CSV Files. https://github.com/davedelong/CHCSVParser

You can find here: Where can I find a CSV to NSArray parser for Objective-C? quite similar problem, btw. converting CSV to JSON should help you parsing data, since JSON could be easily converted to the NSDictionary or NSArray.

I use Numbers create csv and I have problem when I add "," to table.
I use some trick to fix it.
Sorry I try to add sample code here but it too long.
https://github.com/LovePick/CSVParser-Swift

Related

How to read content from plain text remote file with objective-c

I want to read a list (in plain text) from a remote file line by line.
I have found some answers but they're not the ones I'm looking for.
p.s. I've been programing in objective-c and developing in iOS for about 2 months, I'm a rookie i might not understand or recognize some terms. Please answer like you are talking to a beginner.
If i am not wrong you just want to read a text from remote file, so here it is.
NSString * result = NULL;
NSError *err = nil;
NSURL * urlToRequest = [NSURL URLWithString:#"YOUR_REMOTE_FILE_URL"];//like "http://www.example.org/abc.txt"
if(urlToRequest)
{
result = [NSString stringWithContentsOfURL: urlToRequest
encoding:NSUTF8StringEncoding error:&err];
}
if(!err){
NSLog(#"Result::%#",result);
}
To load the remote txt file, you should take a look at NSURLConnection or AFNetworking (there are other possibilities, these two are probably the most common).
You will then get the content of the file. Depending on what you intend to do with it, you may have to parse it, either with something as simple as -[NSString componentsSeparatedByString:] or with something a bit more powerful like NSScanner.
There are three steps involved in loading a file
create the object that specifies the location of the file
call the appropriate NSString class method to load the file into a
string
handle the error if the file is not found
In step 1, you need to either create an NSString with the full path to the file in the file system, or you need to create an NSURL with the network location of the file. In the example below, the code creates an NSURL since your file is on the network.
In step 2, use the stringWithContentsOfFile method to load a file from the file system, or the stringWithContentsOfURL method to load a file from the network. In either case, you can specify the file encoding, or ask iOS to auto-detect the file encoding. The code below auto detects while loading from the network.
In step 3, the code below dumps the file to the debug console if successful or dumps the error object to the console on failure.
Missing from this code is multithreading. The code will block until the file is loaded. Running the code on a background thread, and properly notifying the main thread when the download is complete, is left as an exercise for the reader.
NSURL *url = [NSURL URLWithString:#"www.example.com/somefile.txt"];
NSStringEncoding encoding;
NSError *error;
NSString *str = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error];
if ( str )
NSLog( #"%#", str );
else
NSLog( #"%#", error );

How to convert Excel file in csv and read data from iphone

I want to make an application that read excel file from url and convert data in to csv file and then i can read the csv file and display the data. how can i do this. please help me.
If you have a .xls file, you can use the open source DHlibxls library to read the file into your app. This is an ObjectiveC framework that wraps a C-based library. The library is quite mature.
How to convert Excel file in csv
Click here
and read data from iphone
//******** Get Data fron CSV file  **********//
NSString *path = [[NSBundle mainBundle] pathForResource:#"NameYourCsvFile" ofType:#"csv"];
NSError* error;
dataStr=[NSString stringWithContentsOfFile:path encoding:NSStringEncodingConversionAllowLossy error:&error ];

Is there a way to create a word document or pdf in xcode 5

I would like to create a word document or a pdf of the NSLog output that I have running right now. Is there a way to do that simply or at all? I have googled the crap out of the issue and have been unable to find a result short of going into xcode and then organizer to find the output. I would prefer to not have to do that.
example:
NSLog(#"X: %.3f Y: %.3f", accelerometer.x, accelerometer.y);
//move this output straight into a word document or something of that nature that can then be pulled from the device later.
Thanks
You can write your NSLogs to a file using a method like this:
- (void)redirectNSLogToDocuments
{
NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [allPaths objectAtIndex:0];
NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:#"yourFile.txt"];
freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}
Then you can convert that file to whatever format you want.
How about this: https://github.com/robbiehanson/CocoaLumberjack
There's a built in file logger that outputs to txt files.
It also offers a lot more control over NSLog and you can easily stop logging without having to comment all the calls out
I actually ended up using CocoaLumberJack which will put it into a .txt document. Now to figure out a way to programmatically move the text file to my hd in linux. :(

Parse RTF file into NSArray - objective C

I'm trying to parse and English Dictionary from an RTF file into an array.
I originally had it working, but I'm not sure why it isn't now.
In the dictionary, each word is separated by a new line (\n). My code so far is:
//loading the dictionary into the file and pull the content from the file into memory
NSData *data = [NSData dataWithContentsOfFile:#"wordList.rtf"];
//convert the bytes from the file into a string
NSString *string = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
//split the string around newline characters to create an array
NSArray *englishDictionary = [string componentsSeparatedByString:#"\n"];
When I try and NSLog it, it just comes up with (null)...
I've already looked at: Objective-C: Reading a file line by line
But couldn't get the answer by Yoon Lee working properly. It prints out with two back slashes at the end as well as lots of unnecessary stuff at the start!
Any help would be greatly appreciated! Cheers!
Try using a plain text (txt) file instead of rtf. RTF files contain formatting information about the text as well. Thats the unnecessary stuff that you see after reading the content.

Exporting Sqlite table data to csv file programatically - xcode iOS 5 (for an ipad app)

I am developing a simple app. I am using sqlite to save data into a table (locally, in app documents folder). I want to problematically export this table data in a csv file and email it to a person. Export SQLite data to Excel in iOS programmatically - I tried this, but its not working... Can anybody give an example application to download? Or the code?
Currently, I am using these commands in command line to convert a db table to csv - .mode, .output out.csv, select * from table;
Please help
Here what i have done to generate csv for tabular data.
Here i have done it for simple testing. but what you need to do is to generate 2d array in such manner to produce NSArray like one i have done in this sample.
Here first component in NSArray is one row for table , second component is for second row of table and likewise...
NSArray *array = [NSArray arrayWithObjects:#"NAME,NUMBER",#"\nbhargavi1,12345",#"\nHiral,23456",#"\nHarish,34567", nil];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename=[NSString stringWithFormat:#"test.csv"];
NSString *filePathLib = [NSString stringWithFormat:#"%#",[docDir stringByAppendingPathComponent:filename]];
[[array componentsJoinedByString:#","] writeToFile:filePathLib atomically:YES encoding:NSUTF8StringEncoding error:NULL];
please implement this. May be this could help you out.
i have implement this in my project and it works for me very nicely

Resources