本例子是创建了一个winform程序,如下图:
本文章只记录讲解打开并查询excel的部分代码。
按钮“选择excel文件” 的代码逻辑如下:
private void button4_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
// openFile.Filter = "Excel(*.xls)|*.xls";
openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
openFile.Multiselect = false;
if (openFile.ShowDialog() == DialogResult.OK)
{
#region 获取文件内容
erpClass _erpClass = new erpClass();
var filePath = openFile.FileName;
string fileType = System.IO.Path.GetExtension(filePath);
textBox3.Text = filePath;
string connStr = "";
if (fileType == ".xls")
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connStr = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + filePath + ";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'"; ;
string sql_F = "";
OleDbConnection conn = null;
OleDbDataAdapter da = null;
try
{
conn = new OleDbConnection(connStr);
conn.Open();
#region 遍历sheet
DataTable table = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
foreach (DataRow item in table.Rows)
{
if (item["Table_Name"].ToString() == "机票对账单$")
{
sql_F = "select * from [" + item["Table_Name"].ToString() + "] ";
da = new OleDbDataAdapter(sql_F, connStr);
dsItem = new DataTable();
da.Fill(dsItem);
}
}
#endregion
}
#endregion
catch (Exception ex)
{
MessageBox.Show("操作失败!异常信息:" + ex.ToString());
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
da.Dispose();
conn.Dispose();
}
}
}
}
运行后,点按钮选择excel文件后获取到的内容如下
说明一下,代码中“Table_Name”指表格中的工作表名称;
Jet 引擎,可以访问 Office 97-2003,但不能访问 Office 2007。
ACE 引擎是随 Office 2007 一起发布的数据库连接组件,既可以访问 Office 2007,也可以访问 Office 97-2003。
另外:Microsoft.ACE.OLEDB.12.0 可以访问正在打开的 Excel 文件,而 Microsoft.Jet.OLEDB.4.0 是不可以的。
所以,在使用不同版本的office时,要注意使用合适的引擎。
如果提示12.0未注册,这里是文件分享下载链接不谢:
链接:https://pan.baidu.com/s/12-81a7JohuEgKixcVUiPSg
提取码:0l9z