函数说明:
:AttachDispatch() 是操作EXCEL的函数,位于CRange类中,可以用来锁定和读取EXCEL中的对应单元格。
CRange::void AttachDispatch(LPDISPATCH lpDispatch,BOOL bAutorelease =1)
lpDispatch:锁定的目标指针。
bAutorelease:是否自动释放。
代码:
{
/*TODO: 在此添加控件通知处理程序代码*/
CString strPath;
CFileDialog file(FALSE ,"xls","Data");
if (file.DoModal() == IDOK)
{
strPath = file.GetPathName(); //获得Excel表格路径
m_Path.SetWindowText(strPath); //通过编辑框显示路径
}
CString strPath;
CFileDialog file(FALSE ,"xls","Data");
if (file.DoModal() == IDOK)
{
strPath = file.GetPathName(); //获得Excel表格路径
m_Path.SetWindowText(strPath); //通过编辑框显示路径
}
//下面的来自:见:http://www.360doc.com/content/13/0614/16/3402399_292842196.shtml
CApplication app;
CWorkbooks books;
CWorkbook book;
CWorksheets sheets;
CWorksheet sheet;
CRange range;
if (!app.CreateDispatch("Excel.Application", NULL)) //创建Excel 2000服务器(启动Excel)
{
AfxMessageBox("创建Excel服务失败!");
exit(1);
}
books.AttachDispatch(app.get_Workbooks());
book.AttachDispatch(books.Add(_variant_t("")));
//book.CreateDispatch()
sheets.AttachDispatch(book.get_Worksheets()); //得到Worksheets
sheet.AttachDispatch(sheets.get_Item(_variant_t("Sheet1")));
range.AttachDispatch(sheet.get_Cells()); //得到全部Cells
CString sText[] = { "编号","姓名","所属部门" };
for (int setnum = 0;setnum<m_Grid.GetItemCount() + 1;setnum++)
{
for (int num = 0;num < 3;num++)
{
if (!setnum)
{
range.put_Item(_variant_t((long)(setnum + 1)), _variant_t((long)(num + 1)),
_variant_t(sText[num]));
}
else
{
range.put_Item(_variant_t((long)(setnum + 1)), _variant_t((long)(num + 1)),
_variant_t(m_Grid.GetItemText(setnum - 1, num)));
}
}
}
book.SaveCopyAs(_variant_t(strPath));
book.put_Saved(true);
//释放对象
range.ReleaseDispatch();
sheet.ReleaseDispatch();
sheets.ReleaseDispatch();
book.ReleaseDispatch();
books.ReleaseDispatch();
app.ReleaseDispatch();
}
CApplication app;
CWorkbooks books;
CWorkbook book;
CWorksheets sheets;
CWorksheet sheet;
CRange range;
if (!app.CreateDispatch("Excel.Application", NULL)) //创建Excel 2000服务器(启动Excel)
{
AfxMessageBox("创建Excel服务失败!");
exit(1);
}
books.AttachDispatch(app.get_Workbooks());
book.AttachDispatch(books.Add(_variant_t("")));
//book.CreateDispatch()
sheets.AttachDispatch(book.get_Worksheets()); //得到Worksheets
sheet.AttachDispatch(sheets.get_Item(_variant_t("Sheet1")));
range.AttachDispatch(sheet.get_Cells()); //得到全部Cells
CString sText[] = { "编号","姓名","所属部门" };
for (int setnum = 0;setnum<m_Grid.GetItemCount() + 1;setnum++)
{
for (int num = 0;num < 3;num++)
{
if (!setnum)
{
range.put_Item(_variant_t((long)(setnum + 1)), _variant_t((long)(num + 1)),
_variant_t(sText[num]));
}
else
{
range.put_Item(_variant_t((long)(setnum + 1)), _variant_t((long)(num + 1)),
_variant_t(m_Grid.GetItemText(setnum - 1, num)));
}
}
}
book.SaveCopyAs(_variant_t(strPath));
book.put_Saved(true);
//释放对象
range.ReleaseDispatch();
sheet.ReleaseDispatch();
sheets.ReleaseDispatch();
book.ReleaseDispatch();
books.ReleaseDispatch();
app.ReleaseDispatch();
}
源代码下载地址 :http://download.csdn.net/detail/u010261063/9405374