C/C++ 读写 Excel

需要库:libxl

下载链接:链接: http://pan.baidu.com/s/1dF9R7WH 密码: 5m4n

官方网址:http://www.libxl.com/

 

代码示例:

1.generate a new spreadsheet from scratch

#include "libxl.h"
using namespace libxl;

int main() 
{
    Book* book = xlCreateBook(); // xlCreateXMLBook() for xlsx
    if(book)
    {
        Sheet* sheet = book->addSheet("Sheet1");
        if(sheet)
        {
            sheet->writeStr(2, 1, "Hello, World !");
            sheet->writeNum(3, 1, 1000);
        }
        book->save("example.xls");
        book->release();
    } 
    return 0;
}

 

2.extract data from an existing spreadsheet

Book* book = xlCreateBook();
if(book)
{
    if(book->load("example.xls"))
    {
        Sheet* sheet = book->getSheet(0);
        if(sheet)
        {
            const wchar_t* s = sheet->readStr(2, 1);
            if(s) wcout << s << endl;

            double d = sheet->readNum(3, 1);
            cout << d << endl;
        }
    }

    book->release();
}

 

3.edit an existing spreadsheet

Book* book = xlCreateBook();
if(book) 
{                
    if(book->load("example.xls"))
    {
        Sheet* sheet = book->getSheet(0);
        if(sheet) 
        {   
            double d = sheet->readNum(3, 1);
            sheet->writeNum(3, 1, d * 2);
            sheet->writeStr(4, 1, "new string");
        }
        book->save("example.xls");
    }

    book->release();   
}

 

4.apply formatting options

Font* font = book->addFont();
font->setName("Impact");
font->setSize(36);        

Format* format = book->addFormat();
format->setAlignH(ALIGNH_CENTER);
format->setBorder(BORDERSTYLE_MEDIUMDASHDOTDOT);
format->setBorderColor(COLOR_RED);
format->setFont(font);
           
Sheet* sheet = book->addSheet("Custom");
if(sheet)
{
    sheet->writeStr(2, 1, "Format", format);
    sheet->setCol(1, 1, 25);
}

book->save("format.xls");

 

ps:若出现“undefined reference to 'xxxx'“错误, 可通过手动链接来解决:

解决方法详见 http://www.cnblogs.com/QQ-1615160629/p/6233866.html

 

posted @ 2016-12-29 17:26  筱陌  阅读(1573)  评论(0编辑  收藏  举报