追加EXCEL的代码
不会VC操作EXCEL,就请同学帮忙,他也不熟悉,给我一段应付了事的代码,谁帮我注释下:
void CTEXTDlg::OnExceltest()
{
// TODO: Add your control notification handler code here
CString strPath = "D:\\test.xls";
COleVariant
covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
_Application ExcelApp;
Workbooks wbsMyBooks;
_Workbook wbMyBook;
Worksheets wssMysheets;
_Worksheet wsMysheet;
Range rgMyRge;
//创建Excel 2000服务器(启动Excel)
if (!ExcelApp.CreateDispatch("Excel.Application",NULL))
{
AfxMessageBox("Create Excel service failure!");
return;
}
ExcelApp.SetVisible(false);
//利用模板文件建立新文档
wbsMyBooks.AttachDispatch(ExcelApp.GetWorkbooks(),true);
wbMyBook = wbsMyBooks.Add(covOptional);
for(int k=1;k<=1000;k++){
//得到Worksheets
wssMysheets.AttachDispatch(wbMyBook.GetWorksheets(),true);
//得到sheet1
wsMysheet.AttachDispatch(wssMysheets.GetItem(_variant_t("sheet1")),true);
//得到全部Cells,此时,rgMyRge是cells的集合
rgMyRge.AttachDispatch(wsMysheet.GetCells(),true);
//设置1行1列的单元的值
rgMyRge.SetItem(_variant_t((long)k),_variant_t((long)1),_variant_t("test1"));
rgMyRge.SetItem(_variant_t((long)k),_variant_t((long)2),_variant_t("test2"));
rgMyRge.SetItem(_variant_t((long)k),_variant_t((long)3),_variant_t("test3"));
rgMyRge.SetItem(_variant_t((long)k),_variant_t((long)4),_variant_t("test4"));
wbMyBook.SaveCopyAs(_variant_t(strPath));
ExcelApp.SetVisible(true);
_sleep(1000);
}
}
他的程序添加了EXCEL类(EXCEL2003):
选择Menu->View->ClassWizade,打开ClassWizade窗口,选择Add Class->From a type library,选择C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE,选择_Application、Workbooks、_Workbook、Worksheets、_Worksheet、Range,加入新类,增加头文件#include "comdef.h" #include "Excel.h"
在BOOL CTEXTApp::InitInstance()中,dlg.DoModal();之前增加代码:
if (CoInitialize(NULL)!=0)
{
AfxMessageBox("初始化COM支持库失败!");
exit(1);
}
在return FALSE; 语句前,加入:
CoUninitialize();
然后新建一个按钮,加入上面那一大段代码。
这段代码可以运行,也在每秒追加数据,可是程序会繁忙的不响应(假死机状态)
请高手给我修改下,我想实现的功能是,每秒向EXCEL追加一行数据。