[英]Read Excel File using OLEDB Connection in C#
I am trying to read a excel file and put data into a datatable in C#.When I try with Excel 97-2003 file format (.xls ) it is working fine.But when I try with Excel workbook format (.xlsx ) it is收到如下错误,
“外部表不是预期的格式。”
这是我的代码段。
string file_name = null;
OpenFileDialog file_d = new OpenFileDialog();
file_d.Filter = "Excel Files (*.xlsx)|*.xlsx|Excel Files (*.xls)|*.xls";
file_d.Title = "Select Attendance Record";
if (file_d.ShowDialog() == DialogResult.OK)
{
file_name = file_d.FileName;
}
String ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file_name + ";Extended Properties=Excel 8.0;";
try
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(ConnectionString);
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
请帮助我解决错误。在此先感谢。
自Office 2007起,“。xlsx”和其他Office文件均为XML格式。 您可以使用OpenXML对其进行读取或写入。
试试这个连接字符串
String ConnectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};Extended Properties=\"Excel 12.0;HDR=YES;\"";
这个对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.