DataGridView显示Excel表格

来源:互联网 发布:大学生艾滋病数据 编辑:程序博客网 时间:2024/05/16 06:15

因为项目需求,要写如题目的功能,现在此记录,同时感谢网上提供资料的人。

功能描述:点击按钮,选择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();   }}


阅读全文
0 0
原创粉丝点击