C++讀寫excel檔案(三)—— 用OLE讀寫
轉自http://blog.csdn.net/yukin_xue/article/details/11209283
參考博文:
http://blog.csdn.net/rekrad/article/details/7666196
http://blog.csdn.net/fullsail/article/details/8449448
http://club.topsage.com/thread-2338554-1-1.html
網上都說C++讀寫EXCEL檔案方法很多,如:ODBC、CSpreadsheet、OLE、Sourceforge 上的幾個EXCEL庫...
我試用了ODBC、CSpreadsheet二個方法,都是通過odbc
然後又試用了OLE方法,經試驗成功,就是比較繁瑣一點, 其他的就沒使用了。下面是OLE的使用步驟:
1. 先確保安裝了microsoft的excel軟體,wps是不行的哦 ~ 因為只有ms的excel軟體才提供了有關的類庫;
2. 選中工程,新增類→MFC→Typelib中的MFC類。
新建一個MFC專案(ExportExcel), 建立完後點擊右鍵,新增--類--MFC--TypeLib中的MFC類,分別從【介面】新增:_Application、_Workbook、_Worksheet、Workbooks、Worksheets到【生成的類】中,到該頁面點新增如下:
3. 點新增完後,注意下,找到相關標頭檔案,註釋紅色那行
//#import "D:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE" no_namespace不刪除則會有莫名其妙編譯錯誤
4. 再次編譯還是會有編譯錯誤:
1>d:\work\yuanxx\exportexcel\exportexcel\crange.h(336) : warning C4003: “DialogBoxA”巨集的實參不足
1>d:\work\yuanxx\exportexcel\exportexcel\crange.h(336) : error C2059: 語法錯誤 : “,”
將DialogBox()改成_DialogBox(),則編譯成功!
5. 重要的一步新增原始碼:
.h檔案: IllusionExcelFile.h
#pragma once
//OLE的標頭檔案
#include "CRange.h"
#include "CWorkbook.h"
#include "CWorkbooks.h"
#include "CWorksheet.h"
#include "CWorksheets.h"
#include "CApplication.h"
///
///用於OLE的方式的EXCEL讀寫,
class IllusionExcelFile
{
public:
//建構函式和解構函式
IllusionExcelFile();
virtual ~IllusionExcelFile();
protected:
///開啟的EXCEL檔名稱
CString open_excel_file_;
///EXCEL BOOK集合,(多個檔案時)
CWorkbooks excel_books_;
///當前使用的BOOK,當前處理的檔案
CWorkbook excel_work_book_;
///EXCEL的sheets集合
CWorksheets excel_sheets_;
///當前使用sheet
CWorksheet excel_work_sheet_;
///當前的操作區域
CRange excel_current_range_;
///是否已經預載入了某個sheet的資料
BOOL already_preload_;
///Create the SAFEARRAY from the VARIANT ret.
COleSafeArray ole_safe_array_;
protected:
///EXCEL的程序例項
static CApplication excel_application_;
public:
///
void ShowInExcel(BOOL bShow);
///檢查一個CELL是否是字串
BOOL IsCellString(long iRow, long iColumn);
///檢查一個CELL是否是數值
BOOL IsCellInt(long iRow, long iColumn);
///得到一個CELL的String
CString GetCellString(long iRow, long iColumn);
///得到整數
int GetCellInt(long iRow, long iColumn);
///得到double的資料
double GetCellDouble(long iRow, long iColumn);
///取得行的總數
int GetRowCount();
///取得列的總數
int GetColumnCount();
///使用某個shet,shit,shit
BOOL LoadSheet(long table_index,BOOL pre_load = FALSE);
///通過名稱使用某個sheet,
BOOL LoadSheet(const char* sheet,BOOL pre_load = FALSE);
///通過序號取得某個Sheet的名稱
CString GetSheetName(long table_index);
///得到Sheet的總數
int GetSheetCount();
///開啟檔案
BOOL OpenExcelFile(const char * file_name);
///關閉開啟的Excel 檔案,有時候開啟EXCEL檔案就要
void CloseExcelFile(BOOL if_save = FALSE);
//另存為一個EXCEL檔案
void SaveasXSLFile(const CString &xls_file);
///取得開啟檔案的名稱
CString GetOpenFileName();
///取得開啟sheet的名稱
CString GetLoadSheetName();
///寫入一個CELL一個int
void SetCellInt(long irow, long icolumn,int new_int);
///寫入一個CELL一個string
void SetCellString(long irow, long icolumn,CString new_string);
public:
///初始化EXCEL OLE
static BOOL InitExcel();
///釋放EXCEL的 OLE
static void ReleaseExcel();
///取得列的名稱,比如27->AA
static char *GetColumnName(long iColumn);
protected:
//預先載入
void PreLoadSheet();
};
.cpp檔案:IllusionExcelFile.cpp
//-----------------------excelfile.cpp----------------
#include "StdAfx.h"
#include "IllusionExcelFile.h"
COleVariant
covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
//
CApplication IllusionExcelFile::excel_application_;
IllusionExcelFile::IllusionExcelFile():
already_preload_(FALSE)
{
}
IllusionExcelFile::~IllusionExcelFile()
{
//
CloseExcelFile();
}
//初始化EXCEL檔案,
BOOL IllusionExcelFile::InitExcel()
{
//建立Excel 2000伺服器(啟動Excel)
if (!excel_application_.CreateDispatch("Excel.Application",NULL))
{
AfxMessageBox("建立Excel服務失敗,你可能沒有安裝EXCEL,請檢查!");
return FALSE;
}
excel_application_.put_DisplayAlerts(FALSE);
return TRUE;
}
//
void IllusionExcelFile::ReleaseExcel()
{
excel_application_.Quit();
excel_application_.ReleaseDispatch();
excel_application_=NULL;
}
//開啟excel檔案
BOOL IllusionExcelFile::OpenExcelFile(const char *file_name)
{
//先關閉
CloseExcelFile();
//利用模板檔案建立新文件
excel_books_.AttachDispatch(excel_application_.get_Workbooks(),true);
LPDISPATCH lpDis = NULL;
lpDis = excel_books_.Add(COleVariant(file_name));
if (lpDis)
{
excel_work_book_.AttachDispatch(lpDis);
//得到Worksheets
excel_sheets_.AttachDispatch(excel_work_book_.get_Worksheets(),true);
//記錄開啟的檔名稱
open_excel_file_ = file_name;
return TRUE;
}
return FALSE;
}
//關閉開啟的Excel 檔案,預設情況不儲存檔案
void IllusionExcelFile::CloseExcelFile(BOOL if_save)
{
//如果已經開啟,關閉檔案
if (open_excel_file_.IsEmpty() == FALSE)
{
//如果儲存,交給使用者控制,讓使用者自己存,如果自己SAVE,會出現莫名的等待
if (if_save)
{
ShowInExcel(TRUE);
}
else
{
//
excel_work_book_.Close(COleVariant(short(FALSE)),COleVariant(open_excel_file_),covOptional);
excel_books_.Close();
}
//開啟檔案的名稱清空
open_excel_file_.Empty();
}
excel_sheets_.ReleaseDispatch();
excel_work_sheet_.ReleaseDispatch();
excel_current_range_.ReleaseDispatch();
excel_work_book_.ReleaseDispatch();
excel_books_.ReleaseDispatch();
}
void IllusionExcelFile::SaveasXSLFile(const CString &xls_file)
{
excel_work_book_.SaveAs(COleVariant(xls_file),
covOptional,
covOptional,
covOptional,
covOptional,
covOptional,
0,
covOptional,
covOptional,
covOptional,
covOptional,
covOptional);
return;
}
int IllusionExcelFile::GetSheetCount()
{
return excel_sheets_.get_Count();
}
CString IllusionExcelFile::GetSheetName(long table_index)
{
CWorksheet sheet;
sheet.AttachDispatch(excel_sheets_.get_Item(COleVariant((long)table_index)),true);
CString name = sheet.get_Name();
sheet.ReleaseDispatch();
return name;
}
//按照序號載入Sheet表格,可以提前載入所有的表格內部資料
BOOL IllusionExcelFile::LoadSheet(long table_index,BOOL pre_load)
{
LPDISPATCH lpDis = NULL;
excel_current_range_.ReleaseDispatch();
excel_work_sheet_.ReleaseDispatch();
lpDis = excel_sheets_.get_Item(COleVariant((long)table_index));
if (lpDis)
{
excel_work_sheet_.AttachDispatch(lpDis,true);
excel_current_range_.AttachDispatch(excel_work_sheet_.get_Cells(), true);
}
else
{
return FALSE;
}
already_preload_ = FALSE;
//如果進行預先載入
if (pre_load)
{
PreLoadSheet();
already_preload_ = TRUE;
}
return TRUE;
}
//按照名稱載入Sheet表格,可以提前載入所有的表格內部資料
BOOL IllusionExcelFile::LoadSheet(const char* sheet,BOOL pre_load)
{
LPDISPATCH lpDis = NULL;
excel_current_range_.ReleaseDispatch();
excel_work_sheet_.ReleaseDispatch();
lpDis = excel_sheets_.get_Item(COleVariant(sheet));
if (lpDis)
{
excel_work_sheet_.AttachDispatch(lpDis,true);
excel_current_range_.AttachDispatch(excel_work_sheet_.get_Cells(), true);
}
else
{
return FALSE;
}
//
already_preload_ = FALSE;
//如果進行預先載入
if (pre_load)
{
already_preload_ = TRUE;
PreLoadSheet();
}
return TRUE;
}
//得到列的總數
int IllusionExcelFile::GetColumnCount()
{
CRange range;
CRange usedRange;
usedRange.AttachDispatch(excel_work_sheet_.get_UsedRange(), true);
range.AttachDispatch(usedRange.get_Columns(), true);
int count = range.get_Count();
usedRange.ReleaseDispatch();
range.ReleaseDispatch();
return count;
}
//得到行的總數
int IllusionExcelFile::GetRowCount()
{
CRange range;
CRange usedRange;
usedRange.AttachDispatch(excel_work_sheet_.get_UsedRange(), true);
range.AttachDispatch(usedRange.get_Rows(), true);
int count = range.get_Count();
usedRange.ReleaseDispatch();
range.ReleaseDispatch();
return count;
}
//檢查一個CELL是否是字串
BOOL IllusionExcelFile::IsCellString(long irow, long icolumn)
{
CRange range;
range.AttachDispatch(excel_current_range_.get_Item (COleVariant((long)irow),COleVariant((long)icolumn)).pdispVal, true);
COleVariant vResult =range.get_Value2();
//VT_BSTR標示字串
if(vResult.vt == VT_BSTR)
{
return TRUE;
}
return FALSE;
}
//檢查一個CELL是否是數值
BOOL IllusionExcelFile::IsCellInt(long irow, long icolumn)
{
CRange range;
range.AttachDispatch(excel_current_range_.get_Item (COleVariant((long)irow),COleVariant((long)icolumn)).pdispVal, true);
COleVariant vResult =range.get_Value2();
//好像一般都是VT_R8
if(vResult.vt == VT_INT || vResult.vt == VT_R8)
{
return TRUE;
}
return FALSE;
}
//
CString IllusionExcelFile::GetCellString(long irow, long icolumn)
{
COleVariant vResult ;
CString str;
//字串
if (already_preload_ == FALSE)
{
CRange range;
range.AttachDispatch(excel_current_range_.get_Item (COleVariant((long)irow),COleVariant((long)icolumn)).pdispVal, true);
vResult =range.get_Value2();
range.ReleaseDispatch();
}
//如果資料依據預先載入了
else
{
long read_address[2];
VARIANT val;
read_address[0] = irow;
read_address[1] = icolumn;
ole_safe_array_.GetElement(read_address, &val);
vResult = val;
}
if(vResult.vt == VT_BSTR)
{
str=vResult.bstrVal;
}
//整數
else if (vResult.vt==VT_INT)
{
str.Format("%d",vResult.pintVal);
}
//8位元組的數字
else if (vResult.vt==VT_R8)
{
str.Format("%0.0f",vResult.dblVal);
}
//時間格式
else if(vResult.vt==VT_DATE)
{
SYSTEMTIME st;
VariantTimeToSystemTime(vResult.date, &st);
CTime tm(st);
str=tm.Format("%Y-%m-%d");
}
//單元格空的
else if(vResult.vt==VT_EMPTY)
{
str="";
}
return str;
}
double IllusionExcelFile::GetCellDouble(long irow, long icolumn)
{
double rtn_value = 0;
COleVariant vresult;
//字串
if (already_preload_ == FALSE)
{
CRange range;
range.AttachDispatch(excel_current_range_.get_Item (COleVariant((long)irow),COleVariant((long)icolumn)).pdispVal, true);
vresult =range.get_Value2();
range.ReleaseDispatch();
}
//如果資料依據預先載入了
else
{
long read_address[2];
VARIANT val;
read_address[0] = irow;
read_address[1] = icolumn;
ole_safe_array_.GetElement(read_address, &val);
vresult = val;
}
if (vresult.vt==VT_R8)
{
rtn_value = vresult.dblVal;
}
return rtn_value;
}
//VT_R8
int IllusionExcelFile::GetCellInt(long irow, long icolumn)
{
int num;
COleVariant vresult;
if (already_preload_ == FALSE)
{
CRange range;
range.AttachDispatch(excel_current_range_.get_Item (COleVariant((long)irow),COleVariant((long)icolumn)).pdispVal, true);
vresult = range.get_Value2();
range.ReleaseDispatch();
}
else
{
long read_address[2];
VARIANT val;
read_address[0] = irow;
read_address[1] = icolumn;
ole_safe_array_.GetElement(read_address, &val);
vresult = val;
}
//
num = static_cast<int>(vresult.dblVal);
return num;
}
void IllusionExcelFile::SetCellString(long irow, long icolumn,CString new_string)
{
COleVariant new_value(new_string);
CRange start_range = excel_work_sheet_.get_Range(COleVariant("A1"),covOptional);
CRange write_range = start_range.get_Offset(COleVariant((long)irow -1),COleVariant((long)icolumn -1) );
write_range.put_Value2(new_value);
start_range.ReleaseDispatch();
write_range.ReleaseDispatch();
}
void IllusionExcelFile::SetCellInt(long irow, long icolumn,int new_int)
{
COleVariant new_value((long)new_int);
CRange start_range = excel_work_sheet_.get_Range(COleVariant("A1"),covOptional);
CRange write_range = start_range.get_Offset(COleVariant((long)irow -1),COleVariant((long)icolumn -1) );
write_range.put_Value2(new_value);
start_range.ReleaseDispatch();
write_range.ReleaseDispatch();
}
//
void IllusionExcelFile::ShowInExcel(BOOL bShow)
{
excel_application_.put_Visible(bShow);
excel_application_.put_UserControl(bShow);
}
//返回開啟的EXCEL檔名稱
CString IllusionExcelFile::GetOpenFileName()
{
return open_excel_file_;
}
//取得開啟sheet的名稱
CString IllusionExcelFile::GetLoadSheetName()
{
return excel_work_sheet_.get_Name();
}
//取得列的名稱,比如27->AA
char *IllusionExcelFile::GetColumnName(long icolumn)
{
static char column_name[64];
size_t str_len = 0;
while(icolumn > 0)
{
int num_data = icolumn % 26;
icolumn /= 26;
if (num_data == 0)
{
num_data = 26;
icolumn--;
}
column_name[str_len] = (char)((num_data-1) + 'A' );
str_len ++;
}
column_name[str_len] = '\0';
//反轉
_strrev(column_name);
return column_name;
}
//預先載入
void IllusionExcelFile::PreLoadSheet()
{
CRange used_range;
used_range = excel_work_sheet_.get_UsedRange();
VARIANT ret_ary = used_range.get_Value2();
if (!(ret_ary.vt & VT_ARRAY))
{
return;
}
//
ole_safe_array_.Clear();
ole_safe_array_.Attach(ret_ary);
}
編譯,成功!
6. 使用
使用時有些地方需要注意,使用不當,執行時會有莫名其妙的報錯。
(1)一定要先在APP的InitInstance()函式中,對話方塊初始化之前呼叫函式:AfxOleInit(); 否則呼叫CreateDispatch("Excel.Application",NULL))總是會失敗(認為:建立Excel服務失敗,你可能沒有安裝EXCEL)
(2)定義一個excel操作物件:IllusionExcelFile excl;
(3)初始化excel相關工作:excl.InitExcel();
(3)開啟excel檔案:excl.OpenExcelFile("D:\\work\\yuanxx\\test\\data\\demo3.xlsx");
(4)現在可以做讀操作了,測試程式碼:
IllusionExcelFile excl;
bool bInit = excl.InitExcel();
bool bRet = excl.OpenExcelFile("D:\\work\\yuanxx\\test\\data\\demo3.xlsx");
CString strSheetName = excl.GetSheetName(1);
bool bLoad = excl.LoadSheet(strSheetName);
int nRow = excl.GetRowCount();
int nCol = excl.GetColumnCount();
for (int i=1; i<=nRow; ++i)
{
for (int j=1; j<=nCol; ++j)
{
CString strValue = excl.GetCellString(i, j);
}
}