VC++6.0操作excel2007文件封装类CExcelServer(OLE/COM)

来源:互联网 发布:windows下vim编辑器 编辑:程序博客网 时间:2024/05/22 03:15

转载请注明出处:VC++6.0操作excel2007文件封装类CExcelServer

参考文章:
1、VC操作Excel文件编程相关内容总结
2、VC++导出数据到Excel
3、VSTO学习笔记(二)Excel对象模型

利用VC操作Excel的方法至少有两种:
1、利用ODBC把Excel文件当成数据库文件,来进行读、写、修改等操作。网上有人编写了CSpreadSheet类,提供支持。
2、利用OLE Automation方法,将Excel当成组件服务器,利用VBA。

本文选择了第2中方式。要利用OLE Automation实现对Excel进行操作,必须与Excel对象模型提供的对象进行交互。Excel提供了数百个可能需要与之交互的对象,下面先了解一下编程中常用到的几个对象。

1) Application 对象:代表整个 Microsoft Excel 应用程序。
2) Workbook 对象:代表一个 Microsoft Excel 工作簿,即Excel文件。
3) Workbooks 对象:包含 Microsoft Excel 中当前打开的所有 Workbook 对象。
4) Worksheet 对象:代表一个工作表。一个工作簿中可以包括多个工作表。
5) Worksheets 对象:代表指定或活动工作簿中所有 Worksheet 对象的集合。
6) Range 对象:代表某一单元格、某一行、某一列、某一选定区域(该区域可包含一个或若干连续单元格区域)。Range对象是Excel操作的重点,对于数据插入、修改、删除都要通过它来实现,Range所表示等同于我们在实际编辑Excel文件时,用鼠标在表单中选择中的区域,选中之后再对其进行单元格修改、删除、合并、设置宽、高、颜色等操作。
7) Chart对象:代表工作簿中的图表。此图表既可以是嵌入的图表(包含在ChartObject对象中),也可以是单独的图表工作表。
8) Charts对象:代表指定或活动工作簿中所有图表工作表的集合。
9) Sheets 对象:代表指定或活动工作簿中所有工作表(可以是Chart对象或者WorkSheet对象)的集合。
10) Font对象:用于设置Range选中的单元格字体格式和颜色。
11) Interior对象:用于设置Range选中的单元格背景格式和颜色。
12) Borders对象:用于设置Range选中的单元格的边框。

其他对象可到msdn去了解:http://msdn.microsoft.com/zh-cn/library/office/ff194068.aspx

调用excel对象方法时,常常会用到一些枚举变量,可以到msdn中查找相关值:http://msdn.microsoft.com/zh-cn/library/office/ff838815.aspx

在操作Excel之前,必须向工程中添加Excel对象,其步骤是: 选择Menu --> View --> ClassWizard,打开ClassWizard 窗口, 选择Add Class -->From a type library,若系统中安装的是Office2000,则在Office 安装目录选择Excel.OLB,如果安装的是Office2003或2007,则选择Excel.exe;然后根据需要选择添加的类(如果要使用下面的CExcelServer封装类,必须加入_Application,Workbooks,_Workbook ,Worksheets,_Work2sheet,Range,Font,Interior,Borders等),向导会在工程中自动生成加入了这些类的Excel.h和Excel.cpp两个文件。在要使用这些导入的类时加入#include "Excel.h"即可。

CExcelServer类头文件

点击(此处)折叠或打开

  1. #if !defined(AFX_EXCELSERVER_H__7495C273_745B_4F87_A729_D057CAA8D2A9__INCLUDED_)
  2. #define AFX_EXCELSERVER_H__7495C273_745B_4F87_A729_D057CAA8D2A9__INCLUDED_

  3. #if _MSC_VER > 1000
  4. #pragma once
  5. #endif // _MSC_VER > 1000
  6. // ExcelServer.h : header file
  7. //

  8. #include <afxcoll.h>
  9. #include "excel.h"

  10. #define InfoMessageBox(strMsg) \
  11. AfxMessageBox(strMsg, MB_OK | MB_ICONINFORMATION)
  12. #define DebugMessageBox(strMsg) \
  13. AfxMessageBox(strMsg, MB_OK | MB_ICONINFORMATION)
  14. #define WarningMessageBox(strMsg) \
  15. AfxMessageBox(strMsg, MB_OK | MB_ICONWARNING)
  16. #define ErrorMessageBox(strMsg) \
  17. AfxMessageBox(strMsg, MB_OK | MB_ICONERROR)

  18. //Excel文件格式
  19. //http://msdn.microsoft.com/zh-cn/library/office/ff198017.aspx
  20. typedef enum
  21. {
  22.     xlCSV                = 6,        //csv
  23.     xlTextWindows        = 20,        //Windows 文本
  24.     xlTextMSDOS            = 21,        //MSDOS 文本
  25.     xlUnicodeText        = 42,        //Unicode 文本
  26.     xlExcel9795            = 43,        //Excel9795
  27.     xlWorkbookNormal    = -4143,    //常规工作簿
  28.     xlExcel12            = 50,        //Excel 12
  29.     xlWorkbookDefault    = 51,        //默认工作簿
  30. } XlFileFormat;

  31. //水平对齐方式
  32. //http://msdn.microsoft.com/zh-cn/library/office/ff840772.aspx
  33. typedef enum
  34. {
  35.     xlHAlignCenter                    = -4108,    //居中对齐
  36.     xlHAlignCenterAcrossSelection    = 7,        //跨列居中
  37.     xlHAlignDistributed                = -4117,    //分散对齐
  38.     xlHAlignFill                    = 5,        //填充
  39.     xlHAlignGeneral                    = 1,        //按数据类型对齐
  40.     xlHAlignJustify                    = -4130,    //两端对齐
  41.     xlHAlignLeft                    = -4131,    //左对齐
  42.     xlHAlignRight                    = -4152,    //右对齐
  43. } XlHAlign;

  44. //垂直对齐方式
  45. //http://msdn.microsoft.com/zh-cn/library/office/ff835305.aspx
  46. typedef enum
  47. {
  48.     xlVAlignBottom        = -4107,        //靠下 
  49.     xlVAlignCenter        = -4108,        //居中对齐 
  50.     xlVAlignDistributed    = -4117,        //分散对齐 
  51.     xlVAlignJustify        = -4130,        //两端对齐 
  52.     xlVAlignTop            = -4160,        //靠上 
  53. } XlVAlign;

  54. //插入时单元格的移动方向
  55. //http://msdn.microsoft.com/zh-cn/library/office/ff837618.aspx
  56. typedef enum
  57. {
  58.     xlShiftDown        = -4121,        //向下移动单元格
  59.     xlShiftToRight     = -4161,        //向右移动单元格
  60. } XlInsertShiftDirection;

  61. //边框的线条样式
  62. //http://msdn.microsoft.com/zh-cn/library/office/ff821622.aspx
  63. typedef enum
  64. {
  65.     xlContinuous    = 1,        //实线
  66.     xlDash            = -4115,    //虚线
  67.     xlDashDot        = 4,        //点划相间线
  68.     xlDashDotDot    = 5,        //划线后跟两个点
  69.     xlDot            = -4118,    //点式线
  70.     xlDouble        = -4119,    //双线
  71.     xlLineStyleNone    = -4142,    //无线条
  72.     xlSlantDashDot    = 13,        //倾斜的划线
  73. } XlLineStyle;

  74. //边框的粗细
  75. //http://msdn.microsoft.com/zh-cn/library/office/ff197515.aspx
  76. typedef enum
  77. {

  78.     xlHairline        = 1,        //细线(最细的边框)
  79.     xlMedium        = -4138,    //中等
  80.     xlThick            = 4,        //粗(最宽的边框)
  81.     xlThin            = 2,        //
  82. } XlBorderWeight;

  83. /////////////////////////////////////////////////////////////////////////////
  84. // CExcelServer window create by lingdxuyan

  85. class CExcelServer : public CWnd
  86. {
  87. // Construction
  88. public:
  89.     CExcelServer();

  90. // Attributes
  91. private:
  92.     CString            m_strExcelFile;
  93.     CString            m_strWorkSheet;

  94.     _Application    m_oExcelApp;    // Excel程序
  95.     _Worksheet        m_oWorkSheet;    // 工作表
  96.     _Workbook        m_oWorkBook;    // 工作簿
  97.     Workbooks        m_oWorkBooks;    // 工作簿集合
  98.     Worksheets        m_oWorkSheets;    // 工作表集合
  99.     Range            m_oCurrRange;    // 使用区域

  100. // Operations
  101. private:
  102.     //创建Excel服务
  103.     BOOL CreateExcelServer();
  104.     //销毁Excel服务
  105.     void DestroyExcelServer();

  106. public:
  107.     //打开指定工作薄
  108.     BOOL OpenWorkBook(CString strExcelFile);
  109.     //在已打开的工作薄中,打开指定工作薄
  110.     BOOL OpenWorkSheet(CString strWorkSheet);
  111.     //打开指定工作薄和工作表
  112.     BOOL OpenWorkSheet(CString strExcelFile, CString strWorkSheet);
  113.     //关闭当前打开的工作薄
  114.     void CloseWorkBook();
  115.     //关闭工作表
  116.     void CloseWorkSheet();
  117.     //保存工作薄
  118.     void WorkBookSave();
  119.     //将工作薄另存为指定格式
  120.     BOOL WorkBookSaveAs(CString strSaveAsFile, XlFileFormat fileFormat);
  121.     //将工作表另存为指定格式
  122.     void WorkSheetSaveAs(CString strSaveAsFile, XlFileFormat fileFormat);
  123.     //获取当前工作表已使用的行数
  124.     long GetUsedRowsCount();
  125.     //获取当前工作表已使用的列数
  126.     long GetUsedColumnsCount();
  127.     //获取当前工作表中一行数据
  128.     BOOL GetRowString(UINT nRow, CStringArray &array);
  129.     //在指定行插入数据
  130.     void InsertRow(UINT nRow, CStringArray &array);
  131.     //设置指定单元格颜色
  132.     void SetRangeBackgroundColor(CString strStart, CString strEnd, long nColorIndex);
  133.     //设置单元格边框
  134.     void SetRangeBorders(CString strStart, CString strEnd, XlLineStyle lineStyle, 
  135.                                 XlBorderWeight borderWeight);
  136.     //设置单元格外边框
  137.     void SetRangeBorderAround(CString strStart, CString strEnd, XlLineStyle lineStyle, 
  138.                                 XlBorderWeight borderWeight);
  139.     //设置所有单元格的水平对齐和垂直对齐
  140.     void SetAlignment(CString strStart, CString strEnd, XlHAlign hAlign, XlVAlign vAlign);


  141. // Overrides
  142.     // ClassWizard generated virtual function overrides
  143.     //{{AFX_VIRTUAL(CExcelServer)
  144.     //}}AFX_VIRTUAL

  145. // Implementation
  146. public:
  147.     virtual ~CExcelServer();

  148.     // Generated message map functions
  149. protected:
  150.     //{{AFX_MSG(CExcelServer)
  151.         // NOTE - the ClassWizard will add and remove member functions here.
  152.     //}}AFX_MSG
  153.     DECLARE_MESSAGE_MAP()
  154. };

  155. /////////////////////////////////////////////////////////////////////////////

  156. //{{AFX_INSERT_LOCATION}}
  157. // Microsoft Visual C++ will insert additional declarations immediately before the previous line.

  158. #endif // !defined(AFX_EXCELSERVER_H__7495C273_745B_4F87_A729_D057CAA8D2A9__INCLUDED_)

CExcelServer类cpp文件

点击(此处)折叠或打开

  1. // ExcelServer.cpp : implementation file
  2. //

  3. #include "stdafx.h"
  4. #include "ExcelServer.h"
  5. #include <afxtempl.h>

  6. #ifdef _DEBUG
  7. #define new DEBUG_NEW
  8. #undef THIS_FILE
  9. static char THIS_FILE[] = __FILE__;
  10. #endif

  11. /////////////////////////////////////////////////////////////////////////////
  12. // CExcelServer

  13. CExcelServer::CExcelServer()
  14. {
  15.     m_strExcelFile = _T("");
  16.     m_strWorkSheet = _T("");
  17.     CreateExcelServer();
  18. }

  19. CExcelServer::~CExcelServer()
  20. {
  21.     CloseWorkBook();
  22.     DestroyExcelServer();
  23. }


  24. BEGIN_MESSAGE_MAP(CExcelServer, CWnd)
  25.     //{{AFX_MSG_MAP(CExcelServer)
  26.         // NOTE - the ClassWizard will add and remove mapping macros here.
  27.     //}}AFX_MSG_MAP
  28. END_MESSAGE_MAP()


  29. /////////////////////////////////////////////////////////////////////////////
  30. // CExcelServer message handlers

  31. BOOL CExcelServer::CreateExcelServer()
  32. {
  33.     if (0 != CoInitialize(NULL))
  34.     {
  35.         ErrorMessageBox(_T("初始化COM支持库失败!"));
  36.         exit(1);
  37.     }

  38.     //创建Excel服务
  39.     if (!m_oExcelApp.CreateDispatch(_T("Excel.Application"), NULL)) 
  40.     {
  41.         ErrorMessageBox(_T("创建Excel服务失败!")); 
  42.         return FALSE; 
  43.     }

  44.     //设置为显示
  45.     m_oExcelApp.SetVisible(FALSE);

  46.     return TRUE;
  47. }

  48. void CExcelServer::DestroyExcelServer()
  49. {
  50.     m_oExcelApp.ReleaseDispatch();
  51.     m_oExcelApp.Quit(); // 这条语句是推出Excel程序,任务管理器中的EXCEL进程会自动结束。
  52. }

  53. BOOL CExcelServer::OpenWorkBook(CString strExcelFile)
  54. {
  55.     LPDISPATCH lpDisp = NULL;
  56.     COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); 

  57.     CloseWorkBook();
  58.     m_oWorkBooks.AttachDispatch(m_oExcelApp.GetWorkbooks(), TRUE); //没有这条语句,下面打开文件返回失败。
  59.     // 打开文件
  60.     lpDisp = m_oWorkBooks.Open(strExcelFile, 
  61.                  covOptional, 
  62.                  covOptional,
  63.                  covOptional,
  64.                  covOptional,
  65.                  covOptional,
  66.                  covOptional,
  67.                  covOptional,
  68.                  covOptional,
  69.                  covOptional,
  70.                  covOptional,
  71.                  covOptional,
  72.                  covOptional,
  73.                  covOptional,
  74.                  covOptional );
  75.     // 获得活动的WorkBook( 工作簿 )
  76.     m_oWorkBook.AttachDispatch(lpDisp, TRUE);

  77.     // 获得活动的WorkSheet( 工作表 )
  78. //    m_oWorkSheet.AttachDispatch(m_oWorkBook.GetActiveSheet(), TRUE);

  79.     m_strExcelFile = strExcelFile;
  80.     return TRUE;
  81. }

  82. void CExcelServer::CloseWorkBook()
  83. {
  84.     COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
  85.     
  86.     if (!m_strExcelFile.IsEmpty())
  87.     {
  88.         // 关闭
  89.         m_oWorkBook.SetSaved(TRUE); // 将Workbook的保存状态设置为已保存,即不让系统提示是否人工保存
  90.         m_oWorkBook.Close(covOptional, COleVariant(m_strExcelFile), covOptional);
  91.         m_oWorkBooks.Close();
  92.         // 释放
  93.         m_oWorkBook.ReleaseDispatch();
  94.         m_oWorkBooks.ReleaseDispatch();
  95.     }

  96.     m_strExcelFile = _T("");

  97.     CloseWorkSheet();
  98. }

  99. BOOL CExcelServer::OpenWorkSheet(CString strWorkSheet)
  100. {
  101.     CString strMsg;
  102.     long i;

  103.     CloseWorkSheet();

  104.     // 打开工作表集,查找工作表strSheet
  105.     m_oWorkSheets.AttachDispatch( m_oWorkBook.GetWorksheets(), TRUE );
  106.     long lSheetNUM = m_oWorkSheets.GetCount();
  107.     for (i=1; i<=lSheetNUM; i++) 
  108.     { 
  109.         m_oWorkSheet.AttachDispatch( m_oWorkSheets.GetItem(COleVariant((short)i)), TRUE );
  110.         if (strWorkSheet == m_oWorkSheet.GetName())
  111.             break;
  112.     } 

  113.     if (i > lSheetNUM)
  114.     {
  115.         strMsg.Format(_T("在%s中找不到名为%s的表"), m_strExcelFile, strWorkSheet);
  116.         WarningMessageBox(strMsg);
  117.         return FALSE;
  118.     }
  119. #ifdef _DEBUG
  120.     else
  121.     {
  122.         strMsg.Format(_T("%s是%s第%d个表"), strWorkSheet, m_strExcelFile, i);
  123.         DebugMessageBox(strMsg);
  124.     }
  125. #endif

  126.     m_strWorkSheet = strWorkSheet;
  127.     return TRUE;
  128. }

  129. BOOL CExcelServer::OpenWorkSheet(CString strExcelFile, CString strWorkSheet)
  130. {
  131.     if (!OpenWorkBook(strExcelFile))
  132.         return FALSE;

  133.     return OpenWorkSheet(strWorkSheet);
  134. }

  135. void CExcelServer::CloseWorkSheet()
  136. {
  137.     if (!m_strWorkSheet.IsEmpty())
  138.     {
  139.         m_oCurrRange.ReleaseDispatch();
  140.         m_oWorkSheet.ReleaseDispatch();
  141.         m_oWorkSheets.ReleaseDispatch();
  142.     }

  143.     m_strWorkSheet = _T("");
  144. }

  145. long CExcelServer::GetUsedRowsCount()
  146. {
  147.     // 获得使用的区域Range( 区域 )
  148.     m_oCurrRange.AttachDispatch(m_oWorkSheet.GetUsedRange(), TRUE);

  149.     // 获得使用的行数
  150.     m_oCurrRange.AttachDispatch(m_oCurrRange.GetRows(), TRUE);
  151.     return m_oCurrRange.GetCount();
  152. }

  153. BOOL CExcelServer::GetRowString(UINT nRow, CStringArray &array)
  154. { 
  155.     Range oCurCell;
  156.     CString strMsg;

  157.     // 获得使用的列数
  158.     long lUsedColumnNum = GetUsedColumnsCount();
  159.     
  160.     COleVariant covRow((long)nRow);
  161.     CString strHeader;

  162.     // 遍历列头
  163. #ifdef _DEBUG
  164.     strMsg.Format(_T("row %d:"), nRow);
  165. #endif
  166.     m_oCurrRange.AttachDispatch(m_oWorkSheet.GetUsedRange(), TRUE);
  167.     for (long i=1; i<=lUsedColumnNum; i++)
  168.     {
  169.         if (0 != nRow)
  170.         {
  171.             //获取单元格数据
  172.             oCurCell.AttachDispatch(m_oCurrRange.GetItem(covRow, COleVariant(i)).pdispVal, TRUE);
  173.             strHeader = (oCurCell.GetText()).bstrVal;
  174.         }

  175.         //保存单元格数据
  176.         array.Add(strHeader);
  177. #ifdef _DEBUG
  178.         strMsg += _T(" ") + strHeader;
  179. #endif
  180.     }

  181. #ifdef _DEBUG    
  182.     strHeader.Format(_T("size%d"), array.GetSize());
  183.     strMsg += _T(" ") + strHeader;
  184.     DebugMessageBox(strMsg);
  185. #endif

  186.     return TRUE;    
  187. }

  188. long CExcelServer::GetUsedColumnsCount()
  189. {
  190.     // 获得使用的区域Range( 区域 )
  191.     m_oCurrRange.AttachDispatch(m_oWorkSheet.GetUsedRange(), TRUE);

  192.     // 获得使用的列数
  193.     m_oCurrRange.AttachDispatch( m_oCurrRange.GetColumns(), TRUE );
  194.     return m_oCurrRange.GetCount();
  195. }

  196. void CExcelServer::InsertRow(UINT nRow, CStringArray &array)
  197. {
  198.     COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); 
  199.     long size = array.GetSize();
  200.     CString strCell, strData;
  201.     char cColumn = 'A';
  202.     Font oFont;

  203.     if (nRow < 1)
  204.     {
  205.         WarningMessageBox(_T("%s: 行号必须大于0"));
  206.         return;
  207.     }

  208. #ifdef _DEBUG
  209.     CString strMsg;
  210.     strMsg.Format(_T("row %d:"), nRow);
  211. #endif

  212.     for (long i=1; i<=size; i++)
  213.     {
  214.         //获取每1列第1个单元格
  215.         strCell.Format("%c%d", cColumn++, nRow);
  216.         m_oCurrRange.AttachDispatch(m_oWorkSheet.GetRange(COleVariant(strCell), 
  217.             covOptional), TRUE);

  218.         //当前位置插入单元格
  219.         m_oCurrRange.Insert(COleVariant((short)xlShiftDown), covOptional);
  220.         //设置单元格内容
  221.         m_oCurrRange.AttachDispatch(m_oWorkSheet.GetRange(COleVariant(strCell), 
  222.             covOptional), TRUE);
  223.         strData = array.GetAt(i - 1);
  224.         m_oCurrRange.SetValue2(COleVariant(strData));
  225. #ifdef _DEBUG
  226.         strMsg += _T(" ") + strData;
  227. #endif
  228.         //设置单元格字体加粗
  229.         oFont.AttachDispatch(m_oCurrRange.GetFont(), TRUE);
  230.         oFont.SetBold(COleVariant((short)TRUE));

  231.         //自动列宽
  232.         m_oCurrRange.AttachDispatch(m_oCurrRange.GetEntireColumn(), TRUE);
  233.         m_oCurrRange.AutoFit();
  234.     }

  235. #ifdef _DEBUG
  236.     DebugMessageBox(strMsg);
  237. #endif

  238.     oFont.ReleaseDispatch();
  239. }

  240. void CExcelServer::SetRangeBackgroundColor(CString strStart, CString strEnd, long nColorIndex)
  241. {
  242.     Interior oInterior; 

  243.     //获取单元格区域
  244.     m_oCurrRange.AttachDispatch(m_oWorkSheet.GetRange(COleVariant(strStart), 
  245.         COleVariant(strEnd)), TRUE);

  246.     //设置单元格背景色
  247.     oInterior.AttachDispatch(m_oCurrRange.GetInterior(), TRUE); 
  248.     oInterior.SetColorIndex(COleVariant(nColorIndex));

  249.     oInterior.ReleaseDispatch();
  250. }

  251. void CExcelServer::SetRangeBorders(CString strStart, CString strEnd, 
  252.                     XlLineStyle lineStyle, XlBorderWeight borderWeight)
  253. {
  254.     m_oCurrRange.AttachDispatch(m_oWorkSheet.GetRange(COleVariant(strStart), 
  255.         COleVariant(strEnd)), TRUE);

  256.     // 设置区域内所有单元格的边框 
  257.     Borders oBorders; 
  258.     oBorders.AttachDispatch(m_oCurrRange.GetBorders(), TRUE); 
  259.     oBorders.SetColorIndex(COleVariant((long)1));            // 线的颜色(-4105为自动, 1为黑色) 
  260.     oBorders.SetLineStyle(COleVariant((long)lineStyle)); 
  261.     oBorders.SetWeight(COleVariant((long)borderWeight)); 
  262.     oBorders.ReleaseDispatch();
  263. }

  264. void CExcelServer::SetRangeBorderAround(CString strStart, CString strEnd, 
  265.                     XlLineStyle lineStyle, XlBorderWeight borderWeight)
  266. {
  267.     COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); 

  268.     m_oCurrRange.AttachDispatch(m_oWorkSheet.GetRange(COleVariant(strStart), 
  269.         COleVariant(strEnd)), TRUE);

  270.     //设置外边框
  271.     //线的颜色(-4105为自动, 1为黑色) 
  272.     m_oCurrRange.BorderAround(COleVariant((long)lineStyle), borderWeight, 1, covOptional);
  273. }

  274. void CExcelServer::SetAlignment(CString strStart, CString strEnd, XlHAlign hAlign, XlVAlign vAlign)
  275. {
  276.     // 获得使用的区域Range( 区域 )
  277.     m_oCurrRange.AttachDispatch(m_oWorkSheet.GetRange(COleVariant(strStart), 
  278.         COleVariant(strEnd)), TRUE);
  279.     // 设置水平对齐
  280.     m_oCurrRange.SetHorizontalAlignment(COleVariant((short)hAlign));
  281.     // 设置垂直对齐
  282.     m_oCurrRange.SetVerticalAlignment(COleVariant((short)vAlign));    
  283. }

  284. BOOL CExcelServer::WorkBookSaveAs(CString strSaveAsFile, XlFileFormat fileFormat)
  285. {
  286.     COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); 
  287.     CString strMsg;

  288. #ifdef _DEBUG
  289.     strMsg.Format(_T("excel %s save as %s"), 
  290.         m_strExcelFile, strSaveAsFile);
  291.     DebugMessageBox(strMsg);
  292. #endif

  293.     // 删除strSaveAsFile文件,以免excel另存为strSaveAsFile,磁盘中已存在同名文件
  294.     ::DeleteFile(strSaveAsFile);

  295.     // excel另存为strSaveAsFile
  296.     m_oWorkBook.SaveAs(COleVariant(strSaveAsFile),COleVariant((short)fileFormat),covOptional,
  297.                             covOptional,covOptional,covOptional,0,
  298.                             covOptional,covOptional,covOptional,covOptional,covOptional); 

  299.     return TRUE;    
  300. }

  301. void CExcelServer::WorkSheetSaveAs(CString strSaveAsFile, XlFileFormat fileFormat)
  302. {
  303.     COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); 
  304.     CString strMsg;

  305. #ifdef _DEBUG
  306.     strMsg.Format(_T("excel %s sheet %s save as %s"), 
  307.         m_strExcelFile, m_oWorkSheet.GetName(), strSaveAsFile);
  308.     DebugMessageBox(strMsg);
  309. #endif

  310.     // 删除strSaveAsFile文件,以免excel另存为strSaveAsFile文件,磁盘中已存在同名文件
  311.     ::DeleteFile(strSaveAsFile);

  312.     // excel另存为strSaveAsFile
  313.     m_oWorkSheet.SaveAs(strSaveAsFile,COleVariant((short)fileFormat),covOptional,
  314.                             covOptional,covOptional,covOptional,
  315.                             covOptional,covOptional,covOptional,covOptional); 
  316. }

  317. void CExcelServer::WorkBookSave()
  318. {
  319.     m_oWorkBook.Save();
  320.     m_oWorkBook.SetSaved(TRUE); // 将Workbook的保存状态设置为已保存
  321. }


一个例子

点击(此处)折叠或打开

  1. 先定义一个CExcelServer对象
  2. CExcelServer     m_oExcelServer;    // Excel服务


  3.     //打开xls文件
  4.     m_oExcelServer.OpenWorkSheet(strExcelFile, m_strWorkSheet);
  5.     //插入列头
  6.     m_oExcelServer.InsertRow(1, m_arrayHeaders);

  7.     //设置单元格边框和背景颜色
  8.     CString strStartCell, strEndCell;
  9.     long lUsedRowsNum = m_oExcelServer.GetUsedRowsCount();
  10.     long lUsedColumnsNum = m_oExcelServer.GetUsedColumnsCount();
  11.     strStartCell = "A1";
  12.     strEndCell.Format("%c%d", 'A' + lUsedColumnsNum - 1, lUsedRowsNum);
  13.     m_oExcelServer.SetRangeBorders(strStartCell, strEndCell, xlContinuous, xlThin);
  14.     m_oExcelServer.SetRangeBorderAround(strStartCell, strEndCell, xlDouble, xlThin);
  15.     m_oExcelServer.SetRangeBackgroundColor(strStartCell, strEndCell, 34);

  16.     //设置单元格均为水平居中,垂直居中
  17.     strStartCell.Format("A1");
  18.     strEndCell.Format("%c%d", 'A' + lUsedColumnsNum - 1, lUsedRowsNum);
  19.     m_oExcelServer.SetAlignment(strStartCell, strEndCell, xlHAlignCenter, xlVAlignCenter);

  20.     //保存并关闭Excel文件
  21.     m_oExcelServer.WorkBookSave();
  22.     m_oExcelServer.CloseWorkBook();


CExcelServer类,只在VC++6.0、excel2007测试过!
原文地址:VC++6.0操作excel2007文件封装类CExcelServer    出自lingdxuyan

原创粉丝点击