最近工作需要用MFC操作Excel文件,在网上查阅了资料之后,自己也总结了几个步骤,
新建MFC对话框工程,之后再资源视图的对话框中右击,选择类向导,在新的对话框右上角点击"类型库中的MFC类(T),得到如下对话框所示:
再选择“文件”, 最后在编辑框中填入EXCEL.exe的安装路径,我的是“D:\Program Files\Microsoft Office\Office12\EXCEL.EXE”,
在下面有许多类,我本次只用到了_Application,_Workbook, _Worksheet,Range, Interior这几个类别,依次选择后,分别点击 " > " ,而不是 " >> ",后者是选择全部的类别,搞定后,点击完成,即可在文件资源目录看到新添加的文件,
以上就是关于操作的节约流程,最后给出我自己封装的一个操作类,(PS:只有写文件成员函数,没有读文件成员函数,理解了之后,可以自行封装)。
以下是我的源文件和头文件:(PS : 时间冲忙,可能不太perfact)
ExcelWrapper.h
//////////////////////////////////////////////////////////////////////////
///***********************************//
// compile once
#pragma once
#include "CApplication.h"
#include "CRange.h"
#include "CWorkbook.h"
#include "CWorkbooks.h"
#include "CWorksheet.h"
#include "CWorksheets.h"
#include "Cnterior.h"
#define FRIST_SHEET 1
class CExcelWrapper
{
public:
CExcelWrapper()
{
m_pCovOptional = new COleVariant((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
}
~CExcelWrapper()
{
if(NULL != m_pCovOptional)
{
delete m_pCovOptional;
m_pCovOptional = NULL;
}
}
private:
bool MakeSureCreatePath(CString strPath);
public:
bool CreateInterface();
bool ReleaseInterface();
// attribute
bool SetColWidth(int nCols, int nWidth, bool bIsAutoFit = false);
bool SetRowHeight(int nRows, int nHeight, bool bIsAutoFit = false);
bool SetCellGrid(int nRows, int nCols, int nColorIndex = CExcelWrapper::BLACK);
// operators
public:
bool SetCellText(int nRows, int nCols, LPCTSTR lpszString);
//bool GetCellText(int nRows, int nCols, CString &strText);
bool SetCellColor(int nRows, int nCols, int nColorIndex);
//bool GetCellColor(int nRows, int nCols, int &nColorIndex);
bool SaveExcel(CString strPath);
// define color enum
public:
enum{BLACK = 1, WHITE, RED, GREEN, BLUE, YELLOW, PINK, LIGHTGREEN};
public:
COleVariant *m_pCovOptional;
CApplication m_App;
CWorkbooks m_Books;
CWorkbook m_Book;
CWorksheets m_Sheets;
CWorksheet m_Sheet;
CRange m_Range;
Cnterior m_Nterior;
CRange m_Cols;
CRange m_Rows;
};
ExcelWrapper.cpp
//////////////////////////////////////////////////////////////////////////
///***********************************//
#include "stdafx.h"
#include "CExcelWrapper.h"
#include
// MakeSureDirectoryPathExists-API needs this lib
#pragma comment(lib,"imagehlp.lib")
//////////////////////////////////////////
bool CExcelWrapper::CreateInterface()
{
// 加载 Microsoft Office Excel.exe
if (!m_App.CreateDispatch(_T("Excel.Application")))
{
return false;
}
m_Books = m_App.get_Workbooks();
m_Book = m_Books.Add(*m_pCovOptional);
m_Sheets = m_Book.get_Worksheets();
m_Sheet=m_Sheets.get_Item(COleVariant((short)FRIST_SHEET));
return true;
}
bool CExcelWrapper::ReleaseInterface()
{
// 自适应调整
//保存后再修改 Excel.exe进程会弹提示框
/*m_Cols = m_Range.get_EntireColumn();
m_Cols.AutoFit();*/
// 释放资源
m_Nterior.ReleaseDispatch();
m_Range.ReleaseDispatch();
m_Cols.ReleaseDispatch();
m_Sheet.ReleaseDispatch();
m_Sheets.ReleaseDispatch();
m_Book.ReleaseDispatch();
m_Books.ReleaseDispatch();
// 退出 Microsoft Office Excel.exe
m_App.Quit();
m_App.ReleaseDispatch();
return true;
}
bool CExcelWrapper::SetColWidth(int nCols, int nWidth, bool bIsAutoFit)
{
if(nWidth <= 0 || nCols < 1 || nCols > 702)
return false;
if(!bIsAutoFit)
{
m_Range = m_Sheet.get_Rows();
m_Cols.AttachDispatch(m_Range.get_Item(COleVariant((long)nCols),vtMissing).pdispVal, TRUE);
m_Cols.put_ColumnWidth(COleVariant((long)nWidth));
}
else
{
m_Cols.AutoFit();
}
return true;
}
bool CExcelWrapper::SetRowHeight(int nRows, int nHeight, bool bIsAutoFit)
{
if(nHeight <= 0 || nRows < 1)
return false;
if(!bIsAutoFit)
{
m_Range.AttachDispatch(m_Sheet.get_Rows(),TRUE);
m_Rows.AttachDispatch(m_Range.get_Item(COleVariant((long)nRows),vtMissing).pdispVal, TRUE);
m_Rows.put_RowHeight(COleVariant((long)nHeight));
}
else
{
m_Rows.AutoFit();
}
return true;
}
bool CExcelWrapper::SetCellGrid(int nRows, int nCols, int nColorIndex)
{
if(nCols < 1 || nCols > 702 || nRows < 1)
return false;
CString str;
if(nCols > 26)
{
str.Format(_T("%c%c%d"), (nCols-1) / 26 + 64, (nCols-1) % 26 + 1 + 64, nRows);
}
else
{
str.Format(_T("%c%d"), nCols + 64, nRows);
}
m_Range.AttachDispatch(m_Sheet.get_Range(COleVariant(str),COleVariant(str)));
//LineStyle=线型Weight=线宽ColorIndex=线的颜色(-4105为自动)
m_Range.BorderAround(COleVariant((long)1),(long)2,((long)-4105),vtMissing);
//m_Range.AttachDispatch(m_Sheet.get_Range(COleVariant(_T("A2")),COleVariant(_T("D5"))));
//_variant_t v1; //线型
//_variant_t v2; //宽度
//_variant_t v3; //颜色
//v1.vt=VT_I2;
//v1.lVal=2; // 线的样式:- no line; 1-solid; 2-big dot;3-small dot;4-dash dot; 5-dash dot dot;
//v2.vt=v1.vt
//v2.lVal=3; // 线的粗细程度
//v3.vt=v1.vt;
//v3.lVal=1; // 1-black;2-white;3-red;4-green;5-blue; 6-yellow; 7-pink;8-dark blue;
//m_Range.BorderAround(v1, v2, v3, vtMissing);//设置边框
}
bool CExcelWrapper::SetCellText(int nRows, int nCols, LPCTSTR lpszString)
{
if(NULL == lpszString || nCols < 1 || nCols > 702 || nRows < 1)
return false;
CString str;
if(nCols > 26)
{
str.Format(_T("%c%c%d"), (nCols-1) / 26 + 64, (nCols-1) % 26 + 1 + 64, nRows);
}
else
{
str.Format(_T("%c%d"), nCols + 64, nRows);
}
m_Range = m_Sheet.get_Range(COleVariant(str), COleVariant(str));
m_Range.put_Value2(COleVariant(lpszString));
return true;
}
bool CExcelWrapper::SetCellColor(int nRows, int nCols, int nColorIndex)
{
if(nColorIndex < 1 || nColorIndex > 8 || nCols < 1 || nCols > 702 || nRows < 1)
return false;
CString str;
if(nCols > 26)
{
str.Format(_T("%c%c%d"), (nCols-1) / 26 + 64, (nCols-1) % 26 + 1 + 64, nRows);
}
else
{
str.Format(_T("%c%d"), nCols + 64, nRows);
}
m_Range = m_Sheet.get_Range(COleVariant(str), COleVariant(str));
m_Nterior = m_Range.get_Interior();
m_Nterior.put_ColorIndex(_variant_t(nColorIndex));
return true;
}
bool CExcelWrapper::MakeSureCreatePath(CString strPath)
{
int nSize = strPath.GetLength() * 2 + 1;
wchar_t *pWchar_t = strPath.GetBuffer();
char *pChar = new char[nSize];
if(NULL == pChar)
return false;
memset(pChar, 0, (size_t)nSize);
wcstombs(pChar, pWchar_t, nSize);
if (!MakeSureDirectoryPathExists(pChar))
return false;
delete []pChar;
return true;
}
bool CExcelWrapper::SaveExcel(CString strPath)
{
if(_T("") == strPath)
return false;
MakeSureCreatePath(strPath);
//m_Cols = m_Range.get_EntireColumn();
//m_Cols.AutoFit();
m_Book.SaveCopyAs(COleVariant(strPath));
m_Book.put_Saved(true);
return true;
}
最后给出简单的demo;
CExcelWrapper excel;
excel.CreateInterface();
int nRow = 10, nCol = 10;
// 数据写入
excel.SetCellText(nRow, nCol, _T("LXB"));
CString strPath;
strPath = _T("C:\Excel.xlsx");
excel.SaveExcel(strXlsxPath);
excel.ReleaseInterface();