winfrom导入excel文件

  private DataSet xsldata()            //定义一个dataset并把excel数据读入dataset
        {
            dataGridView1.Rows.Clear();
            OpenFileDialog openFile = new OpenFileDialog();//打开文件对话框。
            openFile.Filter = ("Excel 文件(*.xls)|*.xls");//后缀名。
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string filename = openFile.FileName;  //文件路径             
                string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;IMEX=1'";
                OleDbConnection Conn = new OleDbConnection(strCon);
                string strCom = "SELECT * FROM [sheet1$]";
                Conn.Open();
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, Conn);
                DataSet ds = new DataSet();
                myCommand.Fill(ds, "[sheet1$]");
                Conn.Close();
                Conn.Dispose();
                return ds;    //返回dataset
            }
            else
                return null;
        }
        //导入excel     
        private void toolStripButton1_Click(object sender, EventArgs e)
        {         
            try
            {                
                DataSet ds = xsldata();
                if (ds == null)    //如果录入dataset的数据为空(没有点击导入或者直接退出),则{}不执行
                { }
                else
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dataGridView1.Rows.Add((i + 1).ToString(),
                            ds.Tables[0].Rows[i][0].ToString(),
                            ds.Tables[0].Rows[i][1].ToString(),
                            ds.Tables[0].Rows[i][2].ToString(),
                            ds.Tables[0].Rows[i][3].ToString(),
                            ds.Tables[0].Rows[i][4].ToString(),
                            ds.Tables[0].Rows[i][5].ToString(),
                            ds.Tables[0].Rows[i][6].ToString(),
                            ds.Tables[0].Rows[i][7].ToString(),
                            ds.Tables[0].Rows[i][8].ToString(),
                            ds.Tables[0].Rows[i][9].ToString(),
                            ds.Tables[0].Rows[i][10].ToString()
                           );
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex.ToString() + "导入文件时出错,文件可能正被打开", "提示");
                return;
            }

<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值