3

我正在开发一个 C# 项目,以将数据从 excel 文件读取到 Access 数据库中。我不断收到 type 的异常OleDbException。现在的问题不是我为什么会收到这个错误,而是如何处理它。我收到错误是因为我让用户决定他们要上传哪个文件,而某些文件可能没有正确的标题或格式。这是我正在使用的代码:

带有 ** 的行是引发异常的原因。我试过使用:

  1. catch (OleDbException)
  2. catch {}
  3. 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.");
    }
 }
4

1 回答 1

1

可能是您的连接字符串有问题,或者您没有安装 ACE.OLEDB 库,因此 OleDB 找不到正确的提供程序。查看此页面以获取替代连接字符串,或者您应该能够从此处下载提供程序。

您可能想尝试以下方法:

try
{

       using(OleDbConnection excelConnection = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"", filename)))
       {
        excelConnection .Open();     
          using(OleDbCommand command = new OleDbCommand("SELECT columbia_uni, name, score, submitdate, test from [sheet1$]", excelconn))
          {     
                 command.CommandType = CommandType.Text;
                 using(IDataReader reader = command.ExecuteReader())
                 {
                    while(reader.Read())
                    {
                      //Do something
                    }
                 }    
          }
       }


}
catch(Exception e)
{
    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 Columbia_UNI B1 is Name C1 is Score D1 is Submitdate and E1 is Test.\r\n The actual exception message is: " + e.Message);
}

using 等效于 try/finally,并将确保适当地清理连接、命令和 IDataReader 对象。catch 块应该(几乎)捕获此代码生成的任何异常。

于 2012-04-05T21:15:55.870 回答