xlslib库使用简记

xlslib库使用简记

1 前言

最近需要使用C++结合xlslib库来生成Excel文件,但发现这个库的文档还真难找,找来找去发现唯一的线索是有一个test/目录里面的几个例子而已。

想到以后要不断的和这个库打交道,除非愿意用Python去重写,但吃力不讨好,还是做个笔记,以备不时之需。

2 安装使用

安装是三步:

$ ./configure
$ make
$ make install

源码里面自带的使用例子:

xlslib/xlslib/targets/test/formulas.cpp
xlslib/xlslib/targets/test/mainCPP.cpp

安装后:

  • 头文件目录:
    /usr/local/include/xlslib/
    /usr/local/include/xlslib/xlslib/
  • 库文件:
    /usr/local/lib/libxls.3.dylib
    /usr/local/lib/libxls.a
    /usr/local/lib/libxls.dylib
    /usr/local/lib/libxls.la

3 举例: 生成xls

helloxls.cpp:

#include <string.h>
#include <xlslib/xlslib.h>

using namespace xlslib_core;
using namespace std;

int main (int argc, char *argv[]) {

    workbook wb;

    xf_t* xf = wb.xformat();

    worksheet* ws;

    ws = wb.sheet("sheet1");

    string label = "Hello, World!";

    ws->label(1,2,label,xf);    // 从0开始数,第1行,第2列,即C3

    wb.Dump("workbook.xls");

    return 0;
}

编译运行:

$ g++ helloxls.cpp -lxls -I /usr/local/include/xlslib/ -I /usr/local/include/ -L /usr/local/lib/ -o helloxls
$ ./helloxls
$ ll workbook.xls

PS: 因为对API不熟悉,还是在IDE里面自动补全、提示比较方便。

4 举例: 设置颜色

xlscolor.cpp:

#include <string.h>
#include <xlslib/xlslib.h>

using namespace xlslib_core;
using namespace std;

void test() {
    
    workbook wb;
    
    font_t * _font = wb.font("Calibri");
    _font->SetBoldStyle(BOLDNESS_BOLD);  // 设置粗字体
    
    xf_t* xf = wb.xformat();
    
    xf->SetFont(_font);
    xf->SetFillBGColor(CLR_WHITE);
    xf->SetFillFGColor(CLR_RED);
    
    worksheet* ws;
    
    ws = wb.sheet("sheet1");
    
    
    cell_t * cell;
    
    cell = ws->label(1,2,"hello",xf);    // 从0开始数,第1行,第2列,即C3
    
    cell = ws->label(2,2,"world");
    
    cell->fillfgcolor(CLR_RED);
    cell->fillbgcolor(CLR_WHITE);

    
    range * _range;
    
    _range = ws->rangegroup(0,0,1500,100);   // 设置背景为白色
    _range->cellcolor(CLR_WHITE);
    
    _range = ws->rangegroup(1,2,2,2);
    _range->cellcolor(CLR_GOLD);
    
    
    wb.Dump("workbook.xls");
}

5 举例: 设置列宽

#include <string.h>
#include <xlslib/xlslib.h>

using namespace xlslib_core;
using namespace std;

void test() {
    
    workbook wb;
    worksheet* ws;
    
    ws = wb.sheet("sheet1");
    ws->defaultColwidth(256*10);
    ws->colwidth(2,256*30);
    
    cell_t * cell;
    
    cell = ws->label(1,2,"hello",xf);    // 从0开始数,第1行,第2列,即C3
    cell = ws->label(2,2,"world");
    
    wb.Dump("workbook.xls");
}

 

 
原文地址:https://www.cnblogs.com/timssd/p/5519613.html