摘要:使用Microsoft Office所带的控件来实现代码操作excel表格。
最近由于工作需要,不得不操作Excel,包括基本的数据输入输出、字体设置、颜色设置、单元格的合并、填充色的设置,当然还包括图表的生成以及渐近线的操作等。折腾了许久,项目终于完成了^_^。现在将学习操作Excel的点点滴滴记录下来和大家一同分享,也作为自己的一次总结。
1、Excel的对象模型(有人称其为层次结构)
打开一个Excel工作表,点击“工具”->“宏”->“Visual Basic 编辑器”选项打开VB的编辑器,打开帮助文档,里面“Microsoft Excel Visual Basic 参考”下的“Microsoft Excel 对象模型”展示了完整的Excel的层次结构,是不是有点类似于MFC的继承图表啊?利用帮助文档我们可以找到一些需要的知识,下面介绍一些类:
_Application:表示整个的Excel应用程序,包含一个工作簿集合
Workbooks:工作簿集合,包含N个工作簿(Workbook)
_Workbook:工作簿,包含一个工作表(sheets)集合
Worksheets:工作表集合,包含N个工作表
_Worksheet:工作表,也就是我们在Excel中看到的Sheet1、Sheet2、Sheet3,它是我们操作Excel的基本单位
Range:这是单元格的集合,我们知道Excel是由一个个的单元格组成的,通过Range来操作单元格
Font:用于设置单元格的字体、颜色、字号、粗体设置
Interior:设置底色
Boards:设置区域内所有单元格的边框,如果要设置一组区域的外边框的话用Rang->BorderAround设置
下面用一个具体的例子来说明怎么通过MFC来操作Excel
2、Excel库的插入
在我们MFC的工程中,按Ctrl+W打开MFC类向导对话框,点击“Add Class...”->“From a type Library...”,找到你所使用的excel类型库,我使用的在目录C:/Program Files/Microsoft Office/OFFICE11下的“EXCEL.EXE”文件,查找时文件类型选“All Files”,然后添加我们所需要的类,通常以上列举的前6类是必须的,其它的需要时再添加。我不认为全部添加是一种好的做法,一个我觉得很乱,另外生成的excel.cpp文件会很大。我建议浏览一遍这些类,这样当你做些操作时可以更清楚的知道需要添加哪些类。添加完需要的类后,我们就可以来做一些基本的操作了。
3、Com支持库的初始化
通常在App的InitInstance()里面加入初始化和关闭COM库的操作,在DoModal()调用之前加入初始化的代码:
- if (CoInitialize(NULL) != 0)
- {
- AfxMessageBox("初始化COM支持库失败!");
- exit(1);
- }
在return之前加入CoUninitialize(); 关闭CON库。
4、代码演示一些基本的操作
首先别忘了包含头文件“excel.h”,若用到_variant_t()时,需要包含头文件“comdef.h”和“comutil.h”,否则会出现错误:
“error C2065: '_variant_t' : undeclared identifier”。
下面的代码包括了一些基本的操作:
-
- _Application app;
- Workbooks books;
- _Workbook book;
- Worksheets sheets;
- _Worksheet sheet;
- Range range;
- LPDISPATCH lpDisp;
- COleVariant vResult;
-
- CString str = "";
-
- COleVariant
- covTrue((short)TRUE),
- covFalse((short)FALSE),
- covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
-
-
- if (!app.CreateDispatch("Excel.Application",NULL))
- {
- AfxMessageBox("Create Excel service failure!");
- return;
- }
-
-
-
- app.SetVisible(TRUE);
- books.AttachDispatch(app.GetWorkbooks(),true);
-
-
-
-
-
- lpDisp = books.Open("E://test.xls",
- covOptional, covOptional, covOptional, covOptional,
- covOptional, covOptional, covOptional, covOptional,
- covOptional, covOptional, covOptional, covOptional,
- covOptional, covOptional);
- ASSERT(lpDisp);
-
- book.AttachDispatch(lpDisp);
-
-
- sheets.AttachDispatch(book.GetWorksheets(),true);
-
-
- sheet.AttachDispatch(sheets.GetItem(_variant_t((short)(1))));
-
-
- range.AttachDispatch(sheet.GetCells(),true);
-
-
-
- range.SetItem(_variant_t((LONG)1),_variant_t((LONG)1),_variant_t("hello word!"));
-
-
- range.AttachDispatch(sheet.GetRange(_variant_t("A2"), _variant_t("A2")),true);
- range.SetValue2(_variant_t("2011/02/15"));
-
-
- range.AttachDispatch(sheet.GetRange(_variant_t("A3"), _variant_t("A6")),true);
- range.SetValue2(_variant_t((double)3.14));
-
-
- range.AttachDispatch(sheet.GetRange(_variant_t("A1"), _variant_t("A1")),true);
- range.SetColumnWidth(_variant_t((long)12));
-
-
- range.AttachDispatch(sheet.GetCells(),true);
- range.SetHorizontalAlignment(_variant_t((long)-4108));
- range.SetVerticalAlignment(_variant_t((long)-4108));
-
-
- range.AttachDispatch(range.GetItem(_variant_t((long)(4)),_variant_t((long)(1))).pdispVal );
- vResult =range.GetValue(covOptional);
-
- switch (vResult.vt)
- {
- case VT_BSTR:
- str=vResult.bstrVal;
- break;
- case VT_R8:
- str.Format("%f",vResult.dblVal);
- break;
- case VT_DATE:
- SYSTEMTIME st;
- VariantTimeToSystemTime(vResult.date, &st);
- break;
- case VT_EMPTY:
- str="";
- break;
- }
-
-
- Font ft;
-
- range.AttachDispatch(sheet.GetRange(_variant_t("A3"), _variant_t("A5")),true);
- ft.AttachDispatch(range.GetFont());
- ft.SetName(_variant_t("华文行楷"));
- ft.SetSize(_variant_t((long)12));
-
- ft.SetColor( _variant_t((long) RGB(255, 0, 0) ) );
- ft.SetBold(_variant_t((long)1));
-
- Interior it;
-
- range.AttachDispatch(sheet.GetRange(_variant_t("C3"), _variant_t("E6")),true);
- it.AttachDispatch(range.GetInterior());
- it.SetColorIndex(_variant_t((long)20));
-
- Borders borders;
- borders = range.GetBorders();
- borders.SetColorIndex(_variant_t((long)1));
- borders.SetLineStyle(_variant_t((long)1));
- borders.SetWeight(_variant_t((long)2));
-
-
-
- range.BorderAround(_variant_t((long)9),_variant_t((long)1),_variant_t((long)1),vtMissing);
-
- range.AttachDispatch(sheet.GetRange(_variant_t("C8"), _variant_t("D9")),true);
-
- range.Merge(_variant_t((long)0));
-
-
- book.Save();
-
-
-
-
- range.ReleaseDispatch();
- sheet.ReleaseDispatch();
- sheets.ReleaseDispatch();
- book.ReleaseDispatch();
- books.ReleaseDispatch();
- app.ReleaseDispatch();
[c-sharp] view plain copy
- .h文件:
- #include "comdef.h"
- #include "excel.h"
- class ExcelFile
- {
- public:
- void ShowInExcel(bool bShow);
- CString GetCell(int iRow, int iColumn);
- int GetCellInt(int iRow, int iColumn);
- int GetRowCount();
- int GetColumnCount();
- bool LoadSheet(int iIndex);
- CString GetSheetName(int iIndex);
- static void InitExcel();
- static void ReleaseExcel();
- int GetSheetCount();
- bool Open(CString FileName);
- ExcelFile();
- virtual ~ExcelFile();
- protected:
- private:
- static _Application m_ExcelApp;
-
- Workbooks m_Books;
- _Workbook m_Book;
- Worksheets m_sheets;
- _Worksheet m_sheet;
- Range m_Rge;
- };
- .cpp文件:
- ExcelFile::ExcelFile()
- {
- }
- ExcelFile::~ExcelFile()
- {
- m_Rge.ReleaseDispatch();
- m_sheet.ReleaseDispatch();
- m_sheets.ReleaseDispatch();
- m_Book.ReleaseDispatch();
- m_Books.ReleaseDispatch();
- }
- void ExcelFile::InitExcel()
- {
- //创建Excel 2000服务器(启动Excel)
- if (!m_ExcelApp.CreateDispatch("Excel.Application",NULL))
- {
- AfxMessageBox("创建Excel服务失败!");
- exit(1);
- }
- }
- void ExcelFile::ReleaseExcel()
- {
- m_ExcelApp.ReleaseDispatch();
- }
- bool ExcelFile::Open(CString FileName)
- {
- //打开excel文件
- //利用模板文件建立新文档
- m_Books.AttachDispatch(m_ExcelApp.GetWorkbooks(),true);
- LPDISPATCH lpDis = NULL;
- lpDis = m_Books.Add(_variant_t(FileName)); // 如何判断文件是否打开?
- if (lpDis)
- {
- m_Book.AttachDispatch(lpDis);
- //得到Worksheets
- m_sheets.AttachDispatch(m_Book.GetWorksheets(),true);
- return true;
- }
- return false;
- }
- int ExcelFile::GetSheetCount()
- {
- return m_sheets.GetCount();
- }
- CString ExcelFile::GetSheetName(int iIndex)
- {
- _Worksheet sheet;
- sheet.AttachDispatch(m_sheets.GetItem(_variant_t((long)iIndex)),true);
- CString name = sheet.GetName();
- sheet.ReleaseDispatch();
- return name;
- }
- bool ExcelFile::LoadSheet(int iIndex)
- {
- LPDISPATCH lpDis = NULL;
- m_Rge.ReleaseDispatch();
- m_sheet.ReleaseDispatch();
- lpDis = m_sheets.GetItem(_variant_t((long)iIndex));
- if (lpDis)
- {
- m_sheet.AttachDispatch(lpDis,true);
- m_Rge.AttachDispatch(m_sheet.GetCells(), true);
- return true;
- }
- return false;
- }
- int ExcelFile::GetColumnCount()
- {
- Range range;
- Range usedRange;
- usedRange.AttachDispatch(m_sheet.GetUsedRange(), true);
- range.AttachDispatch(usedRange.GetColumns(), true);
- int count = range.GetCount();
- usedRange.ReleaseDispatch();
- range.ReleaseDispatch();
- return count;
- }
- int ExcelFile::GetRowCount()
- {
- Range range;
- Range usedRange;
- usedRange.AttachDispatch(m_sheet.GetUsedRange(), true);
- range.AttachDispatch(usedRange.GetRows(), true);
- int count = range.GetCount();
- usedRange.ReleaseDispatch();
- range.ReleaseDispatch();
- return count;
- }
- CString ExcelFile::GetCell(int iRow, int iColumn)
- {
- Range range;
- range.AttachDispatch(m_Rge.GetItem (COleVariant((long)iRow),COleVariant((long)iColumn)).pdispVal, true);
- COleVariant vResult =range.GetValue2();
- CString str;
- if(vResult.vt == VT_BSTR) //字符串
- {
- str=vResult.bstrVal;
- }
- else if (vResult.vt==VT_INT)
- {
- str.Format("%d",vResult.pintVal);
- }
- else if (vResult.vt==VT_R8) //8字节的数字
- {
- str.Format("%f",vResult.dblVal);
- //str.Format("%.0f",vResult.dblVal);
- //str.Format("%1f",vResult.fltVal);
- }
- else if(vResult.vt==VT_DATE) //时间格式
- {
- SYSTEMTIME st;
- VariantTimeToSystemTime(vResult.date, &st);
- }
- else if(vResult.vt==VT_EMPTY) //单元格空的
- {
- str="(NULL)";
- }
- range.ReleaseDispatch();
- return str;
- }
- int ExcelFile::GetCellInt(int iRow, int iColumn)
- {
- Range range;
- range.AttachDispatch(m_Rge.GetItem(COleVariant((long)iRow),COleVariant((long)iColumn)).pdispVal, true);
- COleVariant vResult =range.GetValue2();
- int num;
- num = (int)vResult.date;
- range.ReleaseDispatch();
- return num;
- }
- void ExcelFile::ShowInExcel(bool bShow)
- {
- m_ExcelApp.SetVisible(bShow);
- }