如何将excel列名放入C#组合框?
大家好,我正在尝试从电脑中的任何位置获取excel工作表,每当有人浏览并选择excel工作表时,我希望其列名列在组合框中。到目前为止,我已经完成了最难的部分的编码,但我仍然得到了一个小错误,即 Microsoft Access数据库引擎找不到对象“columns”。请确保该对象存在,并且正确拼写其名称和路径名。如果“columns”不是本地对象,请检查网络连接或与服务器管理员联系 但我已经成功地在SQLServer数据库上实现了相同的代码。只有在尝试访问excel工作表时,才会出现此错误。为什么会出现此错误以及如何修复它?多谢各位如何将excel列名放入C#组合框?,c#,excel,vba,C#,Excel,Vba,大家好,我正在尝试从电脑中的任何位置获取excel工作表,每当有人浏览并选择excel工作表时,我希望其列名列在组合框中。到目前为止,我已经完成了最难的部分的编码,但我仍然得到了一个小错误,即 Microsoft Access数据库引擎找不到对象“columns”。请确保该对象存在,并且正确拼写其名称和路径名。如果“columns”不是本地对象,请检查网络连接或与服务器管理员联系 但我已经成功地在SQLServer数据库上实现了相同的代码。只有在尝试访问excel工作表时,才会出现此错误。为什么
private String openfile()
{
string tempPath = "";
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "open MSexcel file ";
fDialog.Filter = "All Files(*.*)|*.*";
fDialog.InitialDirectory = @"C:\";
if (fDialog.ShowDialog() == DialogResult.OK)
{
tempPath = fDialog.FileName;
return tempPath;
}
return null;
}
private void openpath(string path)
{
newconn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source="
+ Convert.ToString(path) + ";Extended Properties=\"Excel 12.0;HDR={1}\";");
}
private void loadtolist()
{
newconn.Open();
cmb.Items.Clear(); //cmb is combo box name
newcmd = new OleDbCommand();
newcmd.Connection = newconn;
newcmd.CommandType = CommandType.Text;
newcmd.CommandText = "SELECT column_name from information_schema.columns where table_name = 'BigData' Order by ordinal_position";
dr = newcmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
cmb.Items.Add(dr[0].ToString());
}
}
dr.Close();
newconn.Close();
}
试试这个
string connectionString = string.Format(Thread.CurrentThread.CurrentCulture, "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;'", excelFilePath);
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = @"SELECT [File], [ItemName], [ItemDescription], [Photographer name], [Date], [Environment site] FROM [Metadata$]";
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
.......
}
}
}
connection.Close();
}
}