【发布时间】:2017-07-21 05:48:45
【问题描述】:
我在我的程序中使用以下 C# 代码使用 oledbconnection 将 excel 97 - 2003 电子表格数据读取到数据表中,并遇到当前上下文中不存在的名称。
DataTable rs = null;
string path = Path.GetFullPath(filePath);
odConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
odConnection.Open();
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dt = odConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = string.Empty;
if (dt != null)
{
sheetName = dt.Rows[0]["Sheet_Name"].ToString();
}
cmd.Connection = odConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
oda = new OleDbDataAdapter(cmd);
oda.Fill(ds, "excelData");
rs = ds.Tables["excelData"];
【问题讨论】:
-
添加更多详细信息。例外,行,你的 excel 有哪些工作表
-
第 3 行,名称 odConnection 在当前上下文中不存在。
-
你没有声明 odConnection 所以它不存在。例如,尝试在
odConnection之前添加var -
@SamvelPetrosov 谢谢,有没有办法过滤一个特定的电子表格而不是循环所有。我有 12 张不同的工作表,而我只对一张电子表格感兴趣。
-
看看我的回答