当Worksheet不存在时处理异常

时间:2013-05-05 20:45:38

标签: c# .net exception exception-handling

我正在尝试使用此代码在不存在Worksheet时处理异常:

int k = blYear.SelectedIndex;
ExcelWorksheet currentWorkSheet;

try
{
    currentWorkSheet = workbook.Worksheets[k + 1];
}
catch (Exception)
{
    MessageBox.Show("La hoja de trabajo no existe en el archivo de Excel", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
    btnCargarExcel.Enabled = true;
    blYear.Enabled = true;
    filePath.Text = "";
}

但我收到了这个错误:

  • 如果我尝试编译此错误,则显示

      

    错误1使用未分配的局部变量'currentWorkSheet'd:\ Work \ ClanMovil \ CMApp \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ ExcelDBUserControl.cs 71 46 CMApp

  • 如果我省略错误并继续构建,那么我会得到另一个

  

--------------------------- Microsoft Visual Studio   ---------------------------源文件:D:\ Work \ ClanMovil \ CMApp \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ ExcelDBUserControl.cs

     

模块:   d:\工作\ ClanMovil \ CMApp \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ BIN \调试\ CMApp.exe

     

处理:[4944] CMApp.vshost.exe

     

源文件与构建模块时不同。你会   像调试器一样使用它?   是否

     

System.Collections.Generic.KeyNotFoundException未处理
  HResult = -2146232969消息=给定的密钥不存在于   字典。 Source = mscorlib StackTrace:          在System.Collections.Generic.Dictionary`2.get_Item(TKey key)          在OfficeOpenXml.ExcelWorksheets.get_Item(Int32 PositionID)          在WindowsFormsApplication1.ExcelDBUserControl.btnCargarExcel_Click(对象   发件人,EventArgs e)in   d:\工作\ ClanMovil \ CMApp \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ ExcelDBUserControl.cs:行   66          在System.Windows.Forms.Control.OnClick(EventArgs e)          在System.Windows.Forms.Button.OnClick(EventArgs e)          在System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)          在System.Windows.Forms.Control.WmMouseUp(消息& m,MouseButtons按钮,Int32点击)          在System.Windows.Forms.Control.WndProc(消息& m)          在System.Windows.Forms.ButtonBase.WndProc(消息& m)          在System.Windows.Forms.Button.WndProc(消息& m)          在System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)          在System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)          在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)          在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)          在System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr)   dwComponentID,Int32原因,Int32 pvLoopData)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32)   原因,ApplicationContext上下文)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32)   原因,ApplicationContext上下文)          在System.Windows.Forms.Application.Run(Form mainForm)          在Windows中的WindowsFormsApplication1.Program.Main()中:\ Work \ ClanMovil \ CMApp \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ Program.cs:line   20          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          在System.Threading.ExecutionContext.RunInternal(ExecutionContext   executionContext,ContextCallback回调,对象状态,布尔值   preserveSyncCtx)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean   preserveSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          在System.Threading.ThreadHelper.ThreadStart()InnerException:

处理这个问题的正确方法是什么?

编辑第一个错误 好的,看到有关未声明的var的错误,我对我的代码进行了一些修改,现在是这样的:

using (var package = new ExcelPackage(existingFile))
{
    ExcelWorkbook workbook = package.Workbook;
    ExcelWorksheet currentWorkSheet = workbook.Worksheets.First();

    if (workbook != null)
    {
        if (workbook.Worksheets.Count > 0)
        {

            int k = blYear.SelectedIndex;

            try
            {
                currentWorkSheet = workbook.Worksheets[k + 1];
            }
            catch (Exception)
            {
                MessageBox.Show("La hoja de trabajo no existe en el archivo de Excel", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnCargarExcel.Enabled = true;
                blYear.Enabled = true;
                filePath.Text = "";
            }

        }
    }
}

但这有一个问题,即使启动了 Exception ,因为这个ExcelWorksheet currentWorkSheet = workbook.Worksheets.First();加载了第一个工作表,这不是我想要实现的。如果我将var定义为ExcelWorksheet currentWorkSheet;并将值设置在第一个条件内,则会出现相同的错误:

  

错误1使用未分配的局部变量'currentWorkSheet'd:\ Work \ ClanMovil \ CMApp \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ ExcelDBUserControl.cs 71 46 CMApp

出现所以我不知道如何处理这个,我被困在这里

1 个答案:

答案 0 :(得分:1)

您的更新代码要好得多。基本上,您需要根据业务逻辑/ UI行为来决定在没有当前工作表时您希望发生什么。你可以在异常处理程序中(或在try之前)设置currentWorksheet = null,然后在catch之外添加额外的逻辑来做...如果currentWorksheet为null,你想做什么。或者只是在catch中放入一个return语句,这样就不会执行以下代码。这取决于你。