因为项目需求,要写如题目的功能,现在此记录,同时感谢网上提供资料的人。
功能描述:点击按钮,选择Excel文件,点击打开,该Excel文件中的数据显示在窗体的DataGridView 中
代码如下
public void ReadExcel()
{
//引入openfiledialog控件,实例化该类
OpenFileDialog openFileDialog=new OpenFileDialog();
//过滤可打开的文件
openFileDialog.Filter="Excel文件|*.xsl;*.xlsx";
//打开文件的路径
string path="";
//打开对话框
if(openFileDialog.ShowDialog==DialogResutl.OK)
{
//获取路径
path=openFileDialog.FileName;
//声明连接字符串
string str="provider=microsoft.jet.loedb.4.0;data source="+path+";extended
properties=excel 8.0";
//创建OleDbConnection 对象
OleDbConnection con=new OleDbConnection();
//打开数据库字符串
con.ConnectionString=str;
//打开连接
con.Open();
//动态获取SHEET名字
DataTable dtSheetName=con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});
string [] strTableNames=new string[dtSheetName.Rows.Count];
for(int i=0;i<dtSheetName.Row[i].Count;i++)
{
strTableNames[i]=dtSheetName.Rows[i]["table_name"].ToString();
}
string conStr="select * from ["+strTableNames[0]+"]";
//OleDbCommand对象
OleDbCommand com=new OleDbCommand(conStr,con);
OleDbAdapter adapter=new OleDbAdapter(com);
DataSet set=new DataSet();
adapter.Fill(set);
dataGridView.DataSource=set.Tables[0];
con.Close();
con.Dispose();
}
}