asp.net 表格EXCEL导入数据库

   protected void btnImport_Click(object sender, EventArgs e)
        {
            int count = 0;
            if (FileUpload1.HasFile == false)//HasFile用来检查FileUpload是否有指定文件
            {
       
                ScriptManager.RegisterClientScriptBlock(this.Page, GetType(), "message", "alert('请您选择Excel文件')", true);
                return;//当无文件时,返回
            }
            string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名
            if (IsXls != ".xls")
            {
       
                ScriptManager.RegisterClientScriptBlock(this.Page, GetType(), "message", "alert('只可以选择Excel文件')", true);
                return;//当选择的不是Excel文件时,返回
            }
            string filename = FileUpload1.FileName;              //获取Execle文件名  DateTime日期函数
            string savePath = Server.MapPath(("\\upfiles\\") + filename);//Server.MapPath 获得虚拟服务器相对路径
            FileUpload1.SaveAs(savePath);                        //SaveAs 将上传的文件内容保存在服务器上
            DataSet ds = ExcelSqlConnection(savePath, filename);           //调用自定义方法
            DataRow[] dr = ds.Tables[0].Select();            //定义一个DataRow数组
            int rowsnum = ds.Tables[0].Rows.Count;
            if (rowsnum == 0)
            {
               //当Excel表为空时,对用户进行提示
                ScriptManager.RegisterClientScriptBlock(this.Page, GetType(), "message", "alert('Excel表为空表,无数据!')", true);
            }
            else
            {
                for (int i = 0; i < dr.Length; i++)
                {
                    //前面除了你需要在建立一个“upfiles”的文件夹外,其他的都不用管了,你只需要通过下面的方式获取Excel的值,然后再将这些值用你的方式去插入到数据库里面
                    string keyUserComName = dr[i]["单位名称"].ToString();
                    string orgCode = dr[i]["组织机构代码证号"].ToString();
                    string keyStartDate = dr[i]["办证日期"].ToString();
                    string keyEndDate = dr[i]["终止日期"].ToString();
                    string postion = dr[i]["县区"].ToString();
                    string businessType = dr[i]["应用扩展"].ToString();
                    string ssCode = dr[i]["单位社会保障号(劳动局)"].ToString();

                    string insertSql = string.Format("insert into Tab_keys (keyUserComName,orgCode,keyStartDate,keyEndDate,postion,businessType,ssCode) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",keyUserComName,orgCode,keyStartDate,keyEndDate,postion,businessType,ssCode);
                    int j = dbHelper.InsertTable(insertSql);
                    count = count + j;
                    //Response.Write("<script>alert('导入内容:" + ex.Message + "')</script>");
                }
                user.userlog.insertLog("导入EXCEL数据"+count.ToString()+"条");
                ScriptManager.RegisterClientScriptBlock(this.Page, GetType(), "message", "alert('Excle表导入成功, 导入数据" + count.ToString() + "条!')", true);
            }

        }

        #region 连接Excel  读取Excel数据   并返回DataSet数据集合
        /// <summary>
        /// 连接Excel  读取Excel数据   并返回DataSet数据集合
        /// </summary>
        /// <param name="filepath">Excel服务器路径</param>
        /// <param name="tableName">Excel表名称</param>
        /// <returns></returns>
        public static System.Data.DataSet ExcelSqlConnection(string filepath, string tableName)
        {
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
            OleDbConnection ExcelConn = new OleDbConnection(strCon);
            try
            {
                string strCom = string.Format("SELECT * FROM [Sheet1$]");
                ExcelConn.Open();
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
                DataSet ds = new DataSet();
                myCommand.Fill(ds, "[" + tableName + "$]");
                ExcelConn.Close();
                return ds;
            }
            catch
            {
                ExcelConn.Close();
                return null;
            }
        }
        #endregion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值