我正在开发一个 C# 项目,以将数据从 excel 文件读取到 Access 数据库中。我不断收到 type 的异常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.");
}
}