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

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;
}


      



  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值