我正在进行一个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.");
}
}发布于 2012-04-05 21:15:55
这可能是连接字符串的问题,或者您没有安装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);
}使用相当于尝试/最后,并将确保适当地清除连接、命令和IDataReader对象。catch块应该捕获(几乎)由此代码生成的任何异常。
https://stackoverflow.com/questions/10035927
复制相似问题