C#如何实现读取excel表格中的数据并显示

使用C#读取Excel文件,在日常开发当中,我们经常会用到,下面的例子是使用OLEDB读取Excel内容,并且把内容显示到一个dataGridView中去。

步骤:

  1. 新建一个form,添加一个button,和一个dataGridView。

    C#如何实现读取excel表格中的数据并显示

  2. 新建一个Excel文档,这里是一个例子,文件

    C#如何实现读取excel表格中的数据并显示

  3. 读取Excel表内容,并且以dataset返回。

     

      public  DataSet getData()

            {

                //打开文件

                OpenFileDialog file = new OpenFileDialog();

                file.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";

                file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                file.Multiselect = false;

                if (file.ShowDialog() == DialogResult.Cancel) 

                    return null;

                //判断文件后缀

                var path = file.FileName;

                string fileSuffix = System.IO.Path.GetExtension(path);

                if (string.IsNullOrEmpty(fileSuffix)) 

                    return null;

     

                using (DataSet ds = new DataSet())

                {

                    //判断Excel文件是2003版本还是2007版本

                    string connString = "";

                    if (fileSuffix == ".xls")

                        connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";

                    else

                        connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";

                    //读取文件

                    string sql_select = " SELECT * FROM [Sheet1$]";

                    using (OleDbConnection conn = new OleDbConnection(connString))

                    using (OleDbDataAdapter cmd = new OleDbDataAdapter(sql_select, conn))

                    {

                        conn.Open();

                        cmd.Fill(ds);

                    }

                    if (ds == null || ds.Tables.Count <= 0) return null;

                    return ds;

                }

            }

  4. Button代码:

     private void button1_Click(object sender, EventArgs e)

            {

                dataGridView1.DataSource = null; //每次打开清空内容

                DataTable dt = getData().Tables[0];

                dataGridView1.DataSource = dt;    

            }

  5. 打开刚刚建立的Excel,也就是我们的目标Excel文档。

    C#如何实现读取excel表格中的数据并显示

  6. 效果如图,内容显示在datagridview中

    C#如何实现读取excel表格中的数据并显示

 

注意事项

  • 这种方式读取表格的时候第一行默认是表头

  • 5
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值