【发布时间】:2012-04-05 20:58:42
【问题描述】:
我正在开发一个 C# 项目,以将数据从 excel 文件读取到 Access 数据库中。我不断收到OleDbException 类型的异常。现在的问题不是我为什么会收到这个错误,而是如何处理它。我收到错误是因为我让用户决定他们要上传哪个文件,而某些文件可能没有正确的标题或格式。这是我正在使用的代码:
带有 ** 的行是引发异常的原因。我试过使用:
catch (OleDbException)catch {}catch (Exception)
但似乎从未将异常抛出到我的 catch 子句中。
public UploadGrades(string filename, OleDbConnection con)
{
this.filename = filename;
this.con = con;
//connect to the file and retrive all data.
excelconn = new OleDbConnection(
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"");;
try
{
excelconn.Open();
OleDbCommand command = new OleDbCommand("SELECT temp, name, score, submitdate, test from [sheet1$]", excelconn);
**reader = command.ExecuteReader();**
}
catch
{
MessageBox.Show("The File " + filename + " cann't be read. It is either in use by a different user \n or it doen't contain the " +
"correct columns. Please ensure that column A1 is temp B1 is Name C1 is Score D1 is Submitdate and E1 is Test.");
}
}
【问题讨论】:
-
你为什么要传递一个连接到方法然后创建一个新的?另外,您确定您正在到达 reader.ExecuteReader() 行吗?您的连接可能会超时,因此您实际上永远不会到达 ExecuteReader 行,并且,如果连接超时足够长,您可能会在抛出异常之前关闭应用程序。或者它可能会在您创建连接时出现,在尝试捕获之外!
-
将尝试向上移动几行,然后执行 catch(Exception ex) { messagebox.show(ex.message) }
-
实际上,尝试将连接实例更改为: new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 ;HDR=YES;IMEX=1\"", 文件名));也。您可能还想测试该文件是否存在,并且是一个完整的 excel 文件。
-
@iterationx 可能是对的。否则,windows 正在做一些愚蠢的事情,这种想法不会是第一次。
-
在 VS 菜单中:Debug + Exceptions,取消勾选。现在你的 catch 处理程序可以工作了 :)