在winfrom选择某个excel文件读取到DataGridView控件中

在b站找的视频,并按照视频做的项目,如有侵权联系本人进行删除。
原视频链接:https://www.bilibili.com/video/BV18e411p7Tr?from=search&seid=4377624564316774647
开发环境:Visual Studio 2019
1.需要在项目引用中引用Microsoft office object LIbrary方法
2.在这里插入图片描述
3.在winform窗体中放入一个botton控件,datagridview,和combox控件
4.在botton的单击事件中进行操作

 DataTableCollection tableCollection;
        private void btnbrowse_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx" })
            {

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtFile.Text = openFileDialog.FileName;
                    using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
                    {
                        using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
                        {
                            DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
                            {
                                ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow = true }
                            });
                            tableCollection = result.Tables;
                            cbosheet.Items.Clear();
                            foreach (DataTable table in tableCollection)
                            cbosheet.Items.Add(table.TableName);//添加到组合框。cbosheet为combox的id

                        }

                    }
                }
            }
        }

5.在这里插入图片描述
6.

  private void cbosheet_SelectedIndexChanged(object sender, EventArgs e)
        {
           
            DataTable dt = tableCollection[cbosheet.SelectedItem.ToString()];
            dataGridView1.DataSource = dt;
        }

 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值