libxls是一個輕量級的讀取excel的xls格式的庫,只能讀不能寫
和其配套的還有一個xlslib庫,只能寫不能讀
可以根據自己的需求選擇使用
讀取代碼:
#include <iostream>
#include <xls.h>
#include <xlsstruct.h>
using namesapce std;
int xlsread(const char* file_path_name)
{
// 工作簿
xlsWorkBook *pWB = NULL;
// 工作表
xlsWorkSheet *pWS = NULL;
// 單元格
xlsCell * cell = NULL;
int sheetIndex;
int row, col;
// 打開文件
pWB = xls_open(file_path_name, "UTF-8");
if (!pWB) {
fprintf(stderr, "Open File Error!\n");
return 2;
}
// 解析xls文件,這個不要忘了
xls_parseWorkBook(pWB);
fprintf(stderr, "Sheet count:%d\n", pWB->sheets.count);
// 讀取每個工作表
for (sheetIndex = 0; sheetIndex < pWB->sheets.count; ++sheetIndex) {
// 獲取工作表
pWS = xls_getWorkSheet(pWB, sheetIndex);
// 解析工作表
xls_parseWorkSheet(pWS);
fprintf(stderr, "Sheet %d name: %s\n", sheetIndex, (char *)pWB->sheets.sheet[sheetIndex].name);
fprintf(stderr, "Sheet Data:\n");
// 每行
for (row = 0; row < pWS->rows.lastrow; ++row) {
// 該行第幾列
for (col = 0; col < pWS->rows.lastcol; ++col) {
// 獲取單元格,這裏也可以通過xls_row獲取到這行的數據,然後,使用row->cells來獲取單元格
cell = xls_cell(pWS, row, col);
// 判斷單元格及內容是否爲空
if (cell && cell->str) {
// 針對數值型進行分別判斷!!很重要
if ( (to_string(cell->d) == (char *)(cell->str)) || // 值較小的數值
( cell->d == 0 && to_string(cell->d).c_str() != (char *)(cell->str))) // 數值域爲 0
{
fprintf(stderr, "%s", (char *)cell->str);
}
else // 較大數值
fprintf(stderr, "%s", to_string(int(cell->d)).c_str());
//fprintf(stderr, "%s", (char *)cell->str);
}
if (col < pWS->rows.lastcol-1) // 逗號分隔
{
fprintf(stderr, ",");
}
}
fprintf(stderr, "\n");
}
fprintf(stderr, "\n");
// 關閉工作表
xls_close_WS(pWS);
}
// 關閉工作簿
xls_close_WB(pWB);
return 0;
}
int main()
{
xlsread("D:/myxls.xls");
return 0;
}
注:上面的demo中,是針對標準的表格,及行列都是一個格子,如果存在合併單元格的情況,則會因爲下標訪問出錯而崩潰,需要自己定義相應的循環規則或讀取條件,避免程序崩潰
同時由於libxls庫存在對數值型讀取異常的問題,在提取單元格數據的時候,要自己進行判定,上面的代碼中已經給出了判斷的例子,可以根據自己的實際需求進行調整