参照用にこの古いスレッドに投稿し、特に LibXL を使用して XLS または XLSX 形式のファイルを読み取るという質問に答えます。以下のコードは、LibXL を使用して Excel ファイルを読み取り、各セルの内容 (値) と型 (数値、文字列、ブール...) を出力する方法を示しています。
// Get the path to the excel file to be opened
NSString *path = [[NSBundle mainBundle] pathForResource:@"FILE_NAME" ofType:@"xlsx"];
// Convert the path into a const char * from an NSString
const char *file = [path cStringUsingEncoding:NSASCIIStringEncoding];
// Create a handle for the excel book (XLSX)
// Use xlCreateBook() for XLS file format
BookHandle book = xlCreateXMLBook();
xlBookLoad(book, file);
// Authorize full use of the library (uncomment below and change values)
//xlBookSetKey(book, "REGISTERED_NAME", "PROVIDED_KEY");
// Determine if the excel file handle is valid
if(xlBookLoad(book, file)){
// We have the book now get the first sheet in the book
SheetHandle sheet = xlBookGetSheet(book, 0);
// Ensure the sheet has been opened as is valid
if(sheet){
// Get the first and last rows of the sheet (determines the length of the parse)
for (int row = xlSheetFirstRow(sheet); row < xlSheetLastRow(sheet); ++row){
// Get the first and last columns of the sheet (determines width of the parse)
for (int col = xlSheetFirstCol(sheet); col < xlSheetLastCol(sheet); ++col){
// When reading the cell pull the type (bool, int, string...)
enum CellType cellType = xlSheetCellType(sheet, row, col);
FormatHandle format = xlSheetCellFormat(sheet, row, col);
NSLog(@"(row = %i, col = %i) = ", row, col);
// Determine if the cell has a formula or is a value w/ format
if (xlSheetIsFormula(sheet, row, col)){
const char* s = xlSheetReadFormula(sheet, row, col, &format);
NSLog(@"%s %s", (s ? s : "null"), "[formula]");
} else{
// The cell is not a formula therefore print the value and type
switch(cellType){
case CELLTYPE_EMPTY: NSLog(@"%s", "[empty]"); break;
case CELLTYPE_NUMBER:{
double d = xlSheetReadNum(sheet, row, col, &format);
NSLog(@"%f %s", d, "[number]");
break;
}
case CELLTYPE_STRING:{
const char* s = xlSheetReadStr(sheet, row, col, &format);
NSLog(@"%s %s", (s ? s : "null"), "[string]");
break;
}
case CELLTYPE_BOOLEAN:{
bool b = xlSheetReadBool(sheet, row, col, &format);
NSLog(@"%s %s", (b ? "true" : "false"), "[boolean]");
break;
}
case CELLTYPE_BLANK: NSLog(@"%s", "[blank]"); break;
case CELLTYPE_ERROR: NSLog(@"%s", "[error]"); break;
}
}
NSLog(@"\n");
}
}
}
}
xlBookRelease(book);