判断excel已经打开


void CAddin1App::Test()
{
 try
 {
  CXlComWorkbooks books(this->GetWorkbooks());
  long lCount = books.GetCount();
  CComVariant varItem;
  CXlComWorkbook book;
  bool bOpen = false;
  for (long lIndex=1;lIndex <= lCount;++lIndex)
  {
   varItem = lIndex;
   book.AttachDispatch(books.GetItem(varItem));
   if (book.GetName() == "testfile.xls")
   {
    AfxMessageBox("the testfile.xls already open");
    bOpen = true;
    break;
   }
  }
  CComVariant vDefault(DISP_E_PARAMNOTFOUND,VT_ERROR);
  //如果没有打开
  if (bOpen == false)
  {
   book.AttachDispatch(books.Open("C:\\testfile.xls",
    vDefault,vDefault,vDefault,vDefault,vDefault,vDefault,vDefault,vDefault,
    vDefault,vDefault,vDefault,vDefault,vDefault,vDefault));
  }

  //读数据
  //.........

  //如果是刚打开的则关闭,否则不关闭
  if (bOpen == false)
  {
   book.Close(vDefault,vDefault,vDefault);
  }
 }
 catch (...) 
 {
  AfxMessageBox("Error");
 }
}

你可能感兴趣的:(判断excel已经打开)