c# 导入

选择按钮 得到路径

    openFileDialog1.FileName = "选择您要输入得文件";
                openFileDialog1.Filter = "Excel2007|*.xlsx|Excel2003|*.xls";
                openFileDialog1.Title = "请选择指定格式的服务器列表文件";
                openFileDialog1.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    this.textBox1.Text = openFileDialog1.FileName;
                }

 

 

确定按钮 导入到页面。

try
            {
                string strConn = "";
                string filePath = openFileDialog1.FileName;

                string str = filePath.Substring(filePath.LastIndexOf(".") + 1, filePath.Length - filePath.LastIndexOf(".") - 1);

                if (str == "xlsx")
                {
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 12.0;";
                }
                else
                {
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source='" + filePath + "';" + "Extended Properties=Excel 8.0;";
                }
                OleDbConnection oleConn = new OleDbConnection(strConn);
                oleConn.Open();
                try
                {
                    OleDbCommand cmd = oleConn.CreateCommand();
                    cmd.CommandText = string.Format(" select * from [{0}$]", "Sheet1");//[sheetName$]要如此格式
                    ///OleDbDataReader odr = cmd.ExecuteReader();
                    OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);

                    this.dgvCardInfo.DataSource = ds.Tables[0];


                }
                finally
                {
                    oleConn.Close();

                    this.textBox1.Text = "选择要导入得路径";
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("选择要导入得路径。");
            }

转载于:https://www.cnblogs.com/dengjie/archive/2011/10/26/2225271.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值