Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from .xls/.csv files into 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?

like image 570
user2903240 Avatar asked Jan 24 '14 16:01

user2903240


2 Answers

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.

like image 148
Jere Käpyaho Avatar answered Oct 13 '22 19:10

Jere Käpyaho


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

like image 34
altyus Avatar answered Oct 13 '22 18:10

altyus