C#oledbexception

时间:2012-04-05 20:58:43

标签: c# oledb

嗨,大家好,我想首先感谢大家提供的好消息。我总是使用stackoverflow但从未问过问题。无论如何,我正在开发一个C#项目,将excel文件中的数据读入Access数据库。我一直得到OleDbException类型的例外。现在问题不是我得到错误的原因,而是如何处理它。我收到错误是因为我让用户决定要上传哪个文件,而某些文件可能没有正确的标题或格式。这是我正在使用的代码: **行是引发异常的行。我尝试过使用:

  1. catch (OleDbException)
  2. catch {}
  3. catch (Exception)
  4. 但似乎异常永远不会抛到我的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.");
        }
     }
    

1 个答案:

答案 0 :(得分:1)

它可能是您的连接字符串有问题,或者您没有安装ACE.OLEDB库,因此OleDB找不到合适的提供程序。请查看alternative connection strings的此页面,或者您应该可以从here下载提供商。

您可能需要尝试以下操作:

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块应该捕获(几乎)此代码生成的任何异常。