Linux C/C++解析xls
libxls作為開源庫,支持在Linux C/C++ 環(huán)境下解析(讀)xls文件,github提供了源碼:
https://github.com/libxls/libxls
但是github的源碼需要一堆輔助工具,才能夠編譯出libxls的C靜態(tài)庫,因此琢磨了下手動編譯libxls的靜態(tài)庫/動態(tài)庫方法,可以擺脫輔助工具缺失乃至版本問題導(dǎo)致的抓狂,尤其適合不方便聯(lián)網(wǎng)的內(nèi)網(wǎng)開發(fā)環(huán)境。
將fuzz、src、include目錄下所有文件拷貝到一個目錄下,修改*.c和*.h文件中指定的include文件路徑為當前目錄下
然后將locale.c、endian.c、fuzz_xls.c、ole.c、xls.c、xlstool.c編譯成相應(yīng)的.o文件
locale.h文件中需要添加語句“#include<stddef.h>”
gcc -c locale.c
gcc -c endian.c
gcc -c ole.c
gcc -c xls.c
gcc -c xlstool.c
gcc -c fuzz_xls.c -std=c99 (fuzz_xls.c源文件需要指定c99標準)
選擇test.c編譯成.o文件
gcc -c test.c
將所有.o文件鏈接在一起生成可執(zhí)行demo程序
gcc locale.o endian.o fuzz_xls.o ole.o xls.o xlstool.o test.o -o demo
也可以將locale.o、endian.o、fuzz_xls.o、ole.o、xls.o、xlstool.o編譯成靜態(tài)庫
ar -rc libxls.a locale.o endian.o fuzz_xls.o ole.o xls.o xlstool.o
gcc -c test.c -L . -lxls -o demo
或者將locale.o、endian.o、fuzz_xls.o、ole.o、xls.o、xlstool.o編譯成動態(tài)庫
gcc -fPIC -shared locale.o endian.o fuzz_xls.o ole.o xls.o xlstool.o -o libxls.so
demo程序鏈接庫
gcc test.c -L . -lxls -o demo
如果想要在C++代碼中使用libxls,需要將XlsReader.cpp和XlsReader.h編譯后鏈接到程序
g++ XlsReader.cpp main.cpp -L. -lxls -o demo -std=c++11
編寫一個xls文件中獲取指定id行的信息的demo:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>#include "XlsReader.h"using namespace std;
using namespace xls;int main(int argc, char *argv[])
{if (argc < 2){cout << "Usage: ./demo <file.xls>" << endl;exit(1);}string width, depth;int id = 3;flaot size[2] = {0};string file = string(argv[1]);WorkBook foo(file);cellContent cell = foo.GetCell(0, 1, 2);for (int sheetNum = 0; sheetNum < foo.GetSheetCount; ++ sheetNum) //遍歷xls所有sheet的列表{if ( "sheet 1" != foo.GetSheetName(sheetNum) ) //選擇sheet 1continue;cout << "find sheet 1." << endl;foo.InitIterator(sheetNum);while (ture){cellContent c = foo.GetNextCell();if (c.type == cellBlank)break;if (c.row == 1)continue;if (c.col == 1){if (stoi(c.str) == id){width.assign(foo.GetCell(sheetNum, c.row, 3).str);depth.assign(foo.GetCell(sheetNum, c.row, 4).str);break; //找到后即退出}}}}size[0] = atof(width.c_str());size[1] = atof(depth.c_str());cout << "Die No. : " << id << ", width: " << size[0] << ", depth: " << size[1] << endl;return 0;
}
總結(jié)
以上是生活随笔為你收集整理的Linux C/C++解析xls的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: flex和bison实例分析
- 下一篇: 摩尔庄园手游黑森林通行证怎么用?