VC操作Excel时SaveAs另存为时选择保存时警告处理

如何自动执行将 Excel 工作表保存为 HTML 文件中使用 Visual c + +

http://support.microsoft.com/kb/199691/zh-cn





VC操作Excel,当用SaveAs保存Excel时,如果待保存路径下已经存在该Excel,则会弹出一个对话框提示你当前路径下已经存在该Excel,是否替换,下面有三个按钮:“是”、“否”、“取消”。如果选择了“取消”则会弹出一个错误警告对话框。

可以按照如下方法解决这个问题:在SaveAs之前添加代码: _Application ExcelApp; ExcelApp.SetAlertBeforeOverwriting(FALSE); ExcelApp.SetDisplayAlerts(FALSE);  

在Office2003版Office所生成的Excel.cpp文件中,类_Workbook的SaveAs函数,其函数原型如下:     void   SaveAs(const   VARIANT&   Filename,       const   VARIANT&   FileFormat,       const   VARIANT&   Password,       const   VARIANT&   WriteResPassword,       const   VARIANT&   ReadOnlyRecommended,       const   VARIANT&   CreateBackup,       long   AccessMode,       const   VARIANT&   ConflictResolution,       const   VARIANT&   AddToMru,       const   VARIANT&   TextCodepage,       const   VARIANT&   TextVisualLayout,       const   VARIANT&   Local);

参数含义参考如下:   Question:       Nothing   like   trying   to   learn/teach   yourself   something   new   to   make   you   humble.   Winbatch   99p,   Excel   97.       I'm   loading   a   tab   delimited   file   {M:\somedir\myfile.txt}   into   Excel   using   OLE   to   manipulate   it   some   &   want   to   save   it   as   an   Excel   .xls   file   {M:\somedir\myfile.txt}.           I   can   get   the   file   to   save   under   the   new   name,   i.e.   with   the   .xls   extension   but   it's   still   in   tab   delimited   format,   NOT   Excel's   native   file   format.   The   following   is   from   a   macro   I   recorded   while   doing   the   action   I   want   to   automate:   ActiveWorkbook.SaveAs   FileName:="M:\TMI_Data\Processed\FEB00.xls",   FileFormat:=xlNormal,   Password:="",   WriteResPassword:="",   ReadOnlyRecommended:=False,   CreateBackup:=False           I   can   get   the   following   code   to   save   the   file   and   add   the   filename   to   the   MRU   list.           fileXL   ="M:\TMI_Data\Processed\FEB00.xls"         Awkbk=ObjXL.ActiveWorkbook       savefile=Awkbk.SaveAs   (fileXL)   ;   this   works           OR       savefile=Awkbk.SaveAs   (   fileXL,   ,   ,   ,   ,   ,@True   )   ;   this   works   the   @True   adds   the   file   to   the   MRU   list.         But,   whenever   I   try   to   insert   something   in   the   position   that   I   think   the   fileformat   stuff   is   supposed   to   go   I   get   1261   OLE   exception   errors   or   3250   OLE   Object   error   :   Problem   occurred   formatting   parameters.   I'm   wondering   if   it's   a   Named   parameter   ?   If   I'm   understanding   the   docs   correctly   (big   IF)   a   named   parameter   would   go   after   all   the   positional   parameters   ?   T/F   ?       I've   tried   a   lot   of   permutations   &   combinations   &   haven't   stumbled   up   on   something   that'll   work   yet.           How   does   one   differentiate   between   /tell   one   from   the   other   on   Named   vice   positional   parameters   ?   I've   looked   in   the   VBA   help   &   haven't   stumbled   onto   anything.           Answer:       Sounds   like   you   almost   have   it.   Positional   parameters   first,   then   the   ::   then   the   parameter=value   pairs   for   the   named   parameters.       Question   (cont'd):       I'm   just   not   grasping   something   here.       I've   tried   the   line   :           savefile=Awkbk.SaveAs   (   fileXL,   ,   ,   ,   ,   ,   ,   ,   ,   ,   ::FileFormat   =   "xlNormal")           with   0   to   10   commas   for   "positional   parameters"   between   the   "fileXL"   &   the   "::".       With   0   or   1   comma   I   get   1261   OLE   exception   Error   &   the   following   entry   from   wwwbatch.ini           [OLE   Exception]     Microsoft   Excel=Unable   to   get   the   SaveAs   property   of   the   Workbook   class         With   2   to   10   commas   I   get   NO   ERRORS,   BUT   while   it   saves   with   an   .xls   extension   it   is   still   Tab   delimited.       How   can   you   tell   if   a   parameter   is   a   "Named   Parameter"   ?           The   VBA   docs   make   the   stuff   all   look   like   "Positional   parameters"           Answer:       Maybe   there   are   three   required   parameters?           Maybe   xlNormal   is   not   a   tring   but   a   constant   and   we   have   to   figure   out   what   number   it   is?           Maybe   cut   and   paste   the   SaveAs   documentation   here   and   we   can   stare   at   it.           Bit   of   an   OLE   tip   that   I   found   a   bit   by   accident.       If   you   want   to   know   whether   something   is   a   string   or   a   constant,   do   it   in   VBA   -   in   this   case,   something   like           var=xlNormal         If   it   bombs   out,   it's   a   string.   If   it   doesn't,   it'll   return   a   value   for   you   to   plug   into   your   scripts.       Here's   the   docs   for   the   "SaveAs   Method"   clipped   direct   from   the   VBA   help   :   Saves   changes   to   the   sheet   (Syntax   1)   or   workbook   (Syntax   2)   in   a   different   file.       Syntax   1       expression.SaveAs(Filename,   FileFormat,   Password,   WriteResPassword,   ReadOnlyRecommended,   CreateBackup,   AddToMru,   TextCodePage,   TextVisualLayout)         Syntax   2     expression.SaveAs(Filename,   FileFormat,   Password,   WriteResPassword,   ReadOnlyRecommended,   CreateBackup,   AccessMode,   ConflictResolution,   AddToMru,   TextCodePage,   TextVisualLayout)         expression   Required.   An   expression   that   returns   a   Chart   or   Worksheet   object   (Syntax   1)   or   a   Workbook   object   (Syntax   2).       Filename   Optional   Variant.   A   string   that   indicates   the   name   of   the   file   to   be   saved.   You   can   include   a   full   path;   if   you   don't,   Microsoft   Excel   saves   the   file   in   the   current   folder.       FileFormat   Optional   Variant.   The   file   format   to   use   when   you   save   the   file.   For   a   list   of   valid   choices,   see   the   FileFormat   property.       Password   Optional   Variant.   A   case-sensitive   string   (no   more   than   15   characters)   that   indicates   the   protection   password   to   be   given   to   the   file.       WriteResPassword   Optional   Variant.   A   string   that   indicates   the   write-reservation   password   for   this   file.   If   a   file   is   saved   with   the   password   and   the   password   isn't   supplied   when   the   file   is   opened,   the   file   is   opened   as   read-only.       ReadOnlyRecommended   Optional   Variant.   True   to   display   a   message   when   the   file   is   opened,   recommending   that   the   file   be   opened   as   read-only.       CreateBackup   Optional   Variant.   True   to   create   a   backup   file.       AccessMode   Optional   Variant.   The   workbook   access   mode.   Can   be   one   of   the   following   XlSaveAsAccessMode   constants:   xlShared   (shared   list),   xlExclusive   (exclusive   mode),   or   xlNoChange   (don't   change   the   access   mode).   If   this   argument   is   omitted,   the   access   mode   isn't   changed.   This   argument   is   ignored   if   you   save   a   shared   list   without   changing   the   file   name.   To   change   the   access   mode,   use   the   ExclusiveAccess   method.       ConflictResolution   Optional   Variant.   Specifies   the   way   change   conflicts   are   resolved   if   the   workbook   is   a   shared   list.   Can   be   one   of   the   following   XlSaveConflictResolution   constants:   xlUserResolution   (display   the   conflict-resolution   dialog   box),   xlLocalSessionChanges   (automatically   accept   the   local   user's   changes),   or   xlOtherSessionChanges   (accept   other   changes   instead   of   the   local   user's   changes).   If   this   argument   is   omitted,   the   conflict-resolution   dialog   box   is   displayed.       AddToMru   Optional   Variant.   True   to   add   this   workbook   to   the   list   of   recently   used   files.   The   default   value   is   False.       TextCodePage   Optional   Variant.   Not   used   in   U.S.   English   Microsoft   Excel.       TextVisualLayout   Optional   Variant.   Not   used   in   U.S.   English   Microsoft   Excel.           Resolution:       GREAT   Tip   --   I   inserted   your   line   into   the   macro   &   then   stepped   thru   it.   It   returned   a   value   of   -4143.   I   plugged   it   into   the   command   like   so:       savefile=Awkbk.SaveAs   (   fileXL,   -4143   ,   ,   ,   ,   ,@True   )         and   SHAZAM   it   works   !   It   would   have   been   A   WHILE   before   I'd   have   stumbled   on   to   that.   Thanks   Again.

参考链接: http://topic.csdn.net/t/20050121/15/3743958.html http://topic.csdn.net/t/20050324/11/3876932.html




////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
本人参考网上做法,利用模板实现了VC对EXCEL的操作,但是存在以下问题:

  1.第一次运行程序,点击保存时没问题,当第二次运行程序时,会弹出对话框,提示已经存在文件,是否替换(是、否、取消),当点击“否”的时候会弹出警告对话框,程序中断;
  2.程序运行后,第一次点击保存时,不会出错,接着再次点击保存时,就会出现警告:无法找到模板......;即程序运行后不能实现多次保存。
  3.程序在关闭后,为何在任务管理器的进程里并没有结束,即不能实现程序在后台也关闭。
  以下是源代码,有劳哪位大侠解惑!不胜感激!
  
  void CTEST::OnConnect()  
{
 // TODO: Add your control notification handler code here
 _Application _app;
  _Workbook _workBook;
 _Worksheet _workSheet;
 Worksheets workSheets;
 Workbooks workBooks;
 Range range;
  _Application ExcelApp;  
 ExcelApp.SetAlertBeforeOverwriting(FALSE);  
 ExcelApp.SetDisplayAlerts(FALSE);   
// LPDISPATCH lpDisp;
 char path[MAX_PATH];
 //VARIANT _variant_t;
 if (CoInitialize(NULL) != 0)
 {
  AfxMessageBox("初始化COM支持库失败!");
  exit(1);
 }  
  if(!_app.CreateDispatch("Excel.Application", NULL))
 {
  MessageBox("创建Excel服务失败!", "信息提示", MB_OK);
  return ;
 }
 //利用模板建立新文档
 _app.SetUserControl(true);
  //_app.SetVisible(true);
 CFileDialog fileDlg(false);
 fileDlg.m_ofn.lpstrFilter="Text Files(*.xls)\0ALL Files(*.*)\0*.*\0\0";
 fileDlg.m_ofn.lpstrDefExt="xls";
 GetCurrentDirectory(MAX_PATH,path);
 CString strPath=path;
 CString Path,Name;
 strPath+="\\模板";
  workBooks=_app.GetWorkbooks();
 _workBook=workBooks.Add(_variant_t(strPath));
  workSheets=_workBook.GetWorksheets();
 _workSheet=workSheets.GetItem(COleVariant((short)1));
 range=_workSheet.GetCells();
 range.SetItem(_variant_t((long)1), _variant_t((long)3), _variant_t("写入数据了"));
 range.SetItem(_variant_t((long)2), _variant_t((long)3), _variant_t("写入数据了"));
 range.SetItem(_variant_t((long)3), _variant_t((long)3), _variant_t("写入数据了"));
 range.SetItem(_variant_t((long)4), _variant_t((long)3), _variant_t("写入数据了"));  
 if(IDOK==fileDlg.DoModal())//这里实现“另存为”对话框
 {
  Path=fileDlg.GetPathName();
 Name=fileDlg.GetFileName();
 //保存数据   
 _workSheet.SaveAs(Path,vtMissing,vtMissing,vtMissing,vtMissing,
  vtMissing,vtMissing,vtMissing,vtMissing,vtMissing);
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 }  
 range.ReleaseDispatch();
 _workSheet.ReleaseDispatch();
 workSheets.ReleaseDispatch();
 _workBook.ReleaseDispatch();
 workSheets.ReleaseDispatch();
 _app.ReleaseDispatch();
  _workBook.Close(vtMissing,COleVariant(Path),vtMissing);
 workBooks.Close();
 _app.Quit();
 CoUninitialize();
}


以上几个问题已经解决,倒腾了一晚上。

(1)将char path[MAX_PATH];
GetCurrentDirectory(MAX_PATH,path);
 CString strPath=path;定义成全局变量,   

(2)workBook.Close(vtMissing,COleVariant(Path),vtMissing);  

  改成_ COleVariant aver((long)DISP_E_PARAMNOTFOUND, VT_ERROR); workBook.Close(aver,COleVariant(Path),aver);

这样的话问题就解决了。




posted on 2010-10-15 10:16 wrh 阅读(6595) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


导航

<2009年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

常用链接

留言簿(19)

随笔档案

文章档案

收藏夹

搜索

最新评论

阅读排行榜

评论排行榜