调用Excel.Workbook.SaveAs后使用Excel.Worksheet.Select时出现异常(HRESULT:0x800AC472)

时间:2013-12-23 05:24:43

标签: c# excel

我正在打开xlsx文件并将每个工作表保存到csv文件中。

以下是保存的相关代码:

int i=0;
foreach (Excel.Worksheet s in app.ActiveWorkbook.Sheets)
{
    s.Select(true); // Error here

    String outfile = outputpath + "("+i+")" + outputfilename + ".csv";
    wkb.SaveAs(outfile, Excel.XlFileFormat.xlCSVMSDOS);

    ++i;
}

输出文件名或路径没有问题,输出文件不存在。它保存前两张然后崩溃。我尝试使用4张不同的输入文件并且它工作得很好,所以它与输入文件有关。

例外

System.Runtime.InteropServices.COMException was unhandled
  HResult=-2146777998
  Message=Exception from HRESULT: 0x800AC472
  Source=ExcelXlsx2Csv
  ErrorCode=-2146777998
  StackTrace:
       at Microsoft.Office.Interop.Excel._Worksheet.Select(Object Replace)
       at ExcelXlsx2Csv.Program.Main(String[] args) in c:\Users\Edward\Documents\Visual Studio 2013\Projects\ExcelXlsx2Csv\ExcelXlsx2Csv\Program.cs:line 109
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

任何提示都赞赏!

3 个答案:

答案 0 :(得分:12)

在我的情况下,抛出了异常,因为我的excel Interop工具显示了一个模态对话框(与过期的许可证密钥相关联 - 对我感到羞耻)。如果我关闭了对话框(已在后台显示),然后点击“继续”#39;在Visual Studio中,程序能够连接到xlsx文件并成功检索数据。

答案 1 :(得分:3)

我认为这是一个具有约束力的问题,我只是用一个:

包围每一个电话(SaveAs,Select)
bool failed = false;
do
{
    try
    {
        // Call goes here
        failed = false;
    }
    catch (System.Runtime.InteropServices.COMException e)
    {
        failed = true;
    }
    System.Threading.Thread.Sleep(10);
} while (failed);

答案 2 :(得分:0)

在我的情况下,有一个相同的异常并检查了任务管理器,其中有很多EXCEL.exe,杀死它们然后运行正常