处理工作表不存在时的异常

本文关键字:异常 不存在 工作 处理 | 更新日期: 2023-09-27 18:12:17

我试图处理工作表不存在时使用此代码的异常:

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' clmovil 'CMApp'WindowsFormsApplication1'WindowsFormsApplication1'ExcelDBUserControl.cs 71 46 CMApp

  • 如果我忽略错误并继续构建然后我得到另一个

--------------------------- 微软Visual Studio---------------------------源文件:D:'Work' clmovil 'CMApp'WindowsFormsApplication1'WindowsFormsApplication1'ExcelDBUserControl.cs

模块:d: ' '工作ClanMovil ' CMApp ' WindowsFormsApplication1 ' WindowsFormsApplication1 ' bin '调试' CMApp.exe

进程:[4944]CMApp.vshost.exe

源文件与构建模块时不同。你会喜欢调试器使用它吗?是否

System.Collections.Generic。KeyNotFoundException未处理
HResult=-2146232969 Message=给定的键不存在于字典。源= mscorlib加:在System.Collections.Generic.Dictionary 2。get_Item (TKey键)在OfficeOpenXml.ExcelWorksheets。get_Item (Int32 PositionID)在WindowsFormsApplication1.ExcelDBUserControl.btnCargarExcel_Click(对象sender, EventArgs e) ind: ' ' 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 (Message&m,鼠标按钮,点击32下)在System.Windows.Forms.Control.WndProc (Message&米)在System.Windows.Forms.ButtonBase.WndProc (Message&米)在System.Windows.Forms.Button.WndProc (Message&米)在System.Windows.Forms.Control.ControlNativeWindow.OnMessage (Message&米)在System.Windows.Forms.Control.ControlNativeWindow.WndProc (Message&米)在System.Windows.Forms.NativeWindow。DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW (MSG&味精)System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop (IntPtrdwComponentID, Int32 reason, Int32 pvLoopData)System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner (Int32原因,ApplicationContext上下文)System.Windows.Forms.Application.ThreadContext.RunMessageLoop (Int32原因,ApplicationContext上下文)在System.Windows.Forms.Application。运行(mainForm形式)在d:'Work' clmovil 'CMApp'WindowsFormsApplication1'WindowsFormsApplication1'Program.cs:line20.在System.AppDomain。_nExecuteAssembly(运行时汇编程序集,字符串[]args)在System.AppDomain。ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ()在System.Threading.ThreadHelper。ThreadStart_Context(对象状态)System.Threading.ExecutionContext.RunInternal (ExecutionContextexecutionContext, ContextCallback, callback,对象状态,布尔值preserveSyncCtx)在System.Threading.ExecutionContext。运行ExecutionContext ExecutionContext, ContextCallback callback,对象状态,布尔值preserveSyncCtx)在System.Threading.ExecutionContext。运行(ExecutionContext, ExecutionContext, ContextCallback, callback, Object state)at System.Threading.ThreadHelper.ThreadStart() InnerException:

正确的处理方法是什么?

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

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' clmovil 'CMApp'WindowsFormsApplication1'WindowsFormsApplication1'ExcelDBUserControl.cs 71 46 CMApp

出现了,我不知道怎么处理,卡在这里了

处理工作表不存在时的异常

更新后的代码要好得多。从本质上讲,您需要从业务逻辑/UI行为中决定当没有当前工作表时想要发生什么。您可以在异常处理程序中设置currentWorksheet = null(或在try之前),然后在catch之外添加额外的逻辑来做…无论你想做什么,如果currentWorksheet为空。或者在catch语句中加入return语句,这样就不会执行下面的代码。