实现拖放读取Excel2007数据表 转处:http://iamsam.blogbus.com/logs/37711535.html

 private void SelectFiles()
        {
            openFileDialog1.Filter = "Excel文件(*.xlsx,*.xls)|*.xlsx;*xls";
            //openFileDialog1.InitialDirectory = path;//指定初始化路径

            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                ExecelFilePath.Text = openFileDialog1.FileName;
            }           
        }

private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string GetDragFileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            if (GetDragFileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))
            {
                ExecelFilePath.Text = GetDragFileName;
                DataSet ds = ExcelToDataSet(GetDragFileName);
                ShowExcel.DataSource = ds.Tables[0];
            }
        }

 

        记得引用 excel 处理类库
        /// <summary>
        /// 读取Excel文件,将内容存储在DataSet中
        /// </summary>
        /// <param name="opnFileName">带路径的Excel文件名</param>
        /// <returns>DataSet</returns>
        private DataSet ExcelToDataSet(string opnFileName)
        {
            string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + opnFileName + ";Extended Properties=\"Excel 12.0;HDR=YES\"";

            if (opnFileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase))
            {
                strCon = " Provider = Microsoft.Jet.OLEDB.4.0; Data Source =" + opnFileName + ";Extended Properties=Excel 8.0";
            }


            OleDbConnection myConn = new OleDbConnection(strCon);
            string strCom = " SELECT * FROM [Sheet1$]";
            myConn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
            DataSet myDataSet = new DataSet();
            myCommand.Fill(myDataSet, "[Sheet1$]");
            myConn.Close();
            return myDataSet;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值