Visual Studio 2010利用libxl读写excel表格数据

时间:2022-08-31 14:30:14

C++读写数据,一般通过txt文件,但是随着数据量的增大,采集数据时运用excel表格的优势得以逐步体现。本文主要介绍一下运用第三方库libxl,对excel表格数据进行读写。分为三个部分,第一部分是Visual Studio2010环境配置,第二部分是读操作,第三部分是写操作。

一、环境配置

1、下载第三方库libxl,网址是http://www.libxl.com/download.html

2、文件包含readme.txt,根据自己的系统对环境进行配置,我的是64位,采取的是Microsoft Visual C++配置。

二、读操作

#include <iostream>
#include <conio.h>
#include "libxl.h"

using namespace libxl;

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

                std::cout << sheet->readNum(4, 1) << std::endl;
                std::cout << sheet->readNum(5, 1) << std::endl;
                const wchar_t* f = sheet->readFormula(6, 1);
                if(f) std::wcout << f << std::endl << std::endl;

                int year, month, day;
                book->dateUnpack(sheet->readNum(8, 1), &year, &month, &day);
                std::cout << year << "-" << month << "-" << day << std::endl;
            }
        }
        else
        {
            std::cout << "At first run generate !" << std::endl;
        }

        book->release();
    }

    std::cout << "\nPress any key to exit...";
    _getch();

    return 0;
}

三、写操作

#include <iostream>
#include <windows.h>
#include "libxl.h"

using namespace libxl;

int main()
{
    Book* book = xlCreateBook();
    if(book)
    {
        Sheet* sheet = book->addSheet(L"Sheet1");
        if(sheet)
        {
            sheet->writeStr(2, 1, L"Hello, World !");
            sheet->writeNum(4, 1, 1000);
            sheet->writeNum(5, 1, 2000);

            Font* font = book->addFont();
            font->setColor(COLOR_RED);
            font->setBold(true);
            Format* boldFormat = book->addFormat();
            boldFormat->setFont(font);
            sheet->writeFormula(6, 1, L"SUM(B5:B6)", boldFormat);

            Format* dateFormat = book->addFormat();
            dateFormat->setNumFormat(NUMFORMAT_DATE);
            sheet->writeNum(8, 1, book->datePack(2008, 4, 29), dateFormat);

            sheet->setCol(1, 1, 12);
        }

        if(book->save(L"example.xls"))
        {
            ::ShellExecute(NULL, L"open", L"example.xls", NULL, NULL, SW_SHOW);
        }
        else
        {
            std::cout << book->errorMessage() << std::endl;
        }

        book->release();
    } 

    return 0;
}