同事教我的方法,很实用~
具体步骤:
新建基于对话框的工程,在对话框CTestDialog中添加按钮:IDC_TEST,双击按钮,添加成员函数:CTest::OnTest()。
1.在InitInstance()中添加:
if(CoInitialize(NULL))
{
AfxMessageBox("初始化Com支持库失败!");
exit(1);
}
在 return FALSE;前面添加:
CoUninitialize();
2.在class wizard中选择Add Class->Add a type from a library,选择路径path(即:本机上的excel安装目录,如本人安装目录为:C:/Program Files/Microsoft Office/OFFICE11/Excel.exe),选择_Applicatin,Workbooks,_Workbook,Worksheets,_Worksheet,Range,这样就在你的工程中自动加入了这几个新类,在file view中可以看到多了excel.h和excel.cpp文件。
3.在TestDialog.cpp中加入:
#include "comdef.h"
#include "excel.h"
4.在void OnTest()中添加:
_Application ExcelApp;
Workbooks wbsMyBooks;
_Workbook wbMyBook;
Worksheets wssMysheets;
_Worksheet wsMysheet;
Range rgMyRge;
COleVariant covTrue((short)TRUE), covFalse((short)FALSE), covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
//取出list值
row = m_list.GetItemCount();
col = m_list.GetHeaderCtrl()->GetItemCount();
if(!row)
{
MessageBox("没有任何记录!","系统提示",MB_OK|MB_ICONEXCLAMATION);
return;
}
//创建Excel 2000服务器(启动Excel)
if (!ExcelApp.CreateDispatch("Excel.Application",NULL))
{
AfxMessageBox("创建Excel服务失败,请检查是否安装Excel!");
exit(1);
}
ExcelApp.SetVisible(false);
//利用模板文件建立新文档
char path[MAX_PATH];
GetCurrentDirectory(MAX_PATH,path);
// CString strPath = path;
// strPath += "//template1";
wbsMyBooks.AttachDispatch(ExcelApp.GetWorkbooks(),true);
// wbMyBook.AttachDispatch(wbsMyBooks.Add(_variant_t(strPath)));
wbMyBook.AttachDispatch(wbsMyBooks.Add(covOptional));
//得到Worksheets
wssMysheets.AttachDispatch(wbMyBook.GetWorksheets(),true);
//得到sheet1
wsMysheet.AttachDispatch(wssMysheets.GetItem(_variant_t("sheet1")),true);
rgMyRge.AttachDispatch(wsMysheet.GetCells(),true);
rgMyRge.SetColumnWidth(_variant_t(long(15)));
for(i=0; i<row; i++)
{
for(j =0;j<col;j++)
{
strList = m_list.GetItemText(i,j);
//设置单元值
rgMyRge.SetItem(_variant_t((long)(i+1)),_variant_t((long)(j+1)),_variant_t(strList));
}
}
//将表格保存
CFileDialog dlg(false);//TRUE为OPEN对话框,FALSE为SAVE AS对话框
if(dlg.DoModal()==IDOK)
{
strPath=dlg.GetPathName();
wsMysheet.SaveAs(strPath,vtMissing,vtMissing,vtMissing,vtMissing,
vtMissing,vtMissing,vtMissing,vtMissing,vtMissing);
ExcelApp.SetVisible(true);
}
//释放对象
wbMyBook.Close(covFalse,covOptional,covOptional);
wbsMyBooks.Close();
ExcelApp.Quit();
rgMyRge.ReleaseDispatch();
wsMysheet.ReleaseDispatch();
wssMysheets.ReleaseDispatch();
wbMyBook.ReleaseDispatch();
wbsMyBooks.ReleaseDispatch();
ExcelApp.ReleaseDispatch();