ASP.Net实现从Excel中读取数据,按列插入到数据库中

1,复盘

工作之后发现日子过得很快,一转眼距离上次发博客已经一周多了,这一周又提升了不少。将在自己电脑上测试成功的代码,整合到了项目相应的模块中。

其中也遇到了挺多困难,首先项目中使用的数据库连接方式跟自己实现的不一样,

也是摸索了一番实现了转换。感觉封装在框架中数据库语句执行更加便捷了。

这是之前的数据库连接方式:

strConnection = ConfigurationManager.ConnectionStrings["wzglConnectionString"].ConnectionString;
con = new SqlConnection(strConnection);
try
{
         con.Open();
         SqlCommand sqlCmd = new SqlCommand();
         sqlCmd.CommandText = sqlStr2;
         sqlCmd.Connection = con;
         SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();
         sqlDataReader.Close();
}
catch (Exception ex)
{
         Response.Write("更新失败,失败原因:" + ex.Message);
}
finally
{
         con.Close();
 }

框架中,数据连接在设置中体现,数据库语句执行方式仅需要调用框架封装的方法即可:

try
{
      bll.GetList1(sqlStrUpdate);
}
catch (Exception ex)
{
       Response.Write("更新失败,失败原因:" + ex.Message);
}       

其次就是数据库的变更,导致SQL语句需要重写,重新测试。这个就是下功夫就可以。但第一天测试的是时候就很怪,明明没有问题的代码就是在页面上显示不出来,倒腾了一下午也没解决,最后也不知道怎么回事就好了,太奇怪了,代码也没改。可能是测试代码在框架中水土不服?

随后遇到的问题就是在GridView中显示全部500多条数据,因此做了分页显示,在插入数据库时,从GridView读取的数据插入就只能插入显示的页面。随后尝试解决方案,对读取Excel文件建立单独的函数,分别在显示和导入数据库的部分进行调用,这样就使用读取Excel中数据的方式直接导入到数据库中。这部分和之前的代码做了更新。之前的业务需求及过程可以看以往的博客。

主要更新部分的代码如下:

//获取Excel数据函数 
public void getExcel()
        {
            string strCon;
            strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("excel1.xls") + "; Extended Properties=Excel 8.0;";
            OleDbConnection olecon = new OleDbConnection(strCon);
            OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strCon);
            myda.Fill(myds);
            GridView1.DataSource = myds;
        }

        
       //这部分前台页面参照之前博客中,点击按钮显示Excel中数据到GridView中
        protected void Button1_Click(object sender, EventArgs e)
        {
            getExcel();
            GridView1.DataBind();
           

        }

        /// 从Excel读取数据循环插入数据到数据库
        protected void Button2_Click(object sender, EventArgs e)
        {
            getExcel();
            for (int i = 0; i < myds.Tables[0].Rows.Count; i++)
            {
                //此处注意和调试结合看SQL语句是否正确
                string sqlStr2 = "insert into [wzglxt].[dbo].[jhmxb]([ID],[sj],[bh],[wlbm],[wlmc],[jldw],[ckdj],[xqslhj],[mtotal],[bz])values";
                sqlStr2 += "('" + (myds.Tables[0].Rows[i][0]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][1]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][2]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][3]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][4]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][5]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][6]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][7]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][8]).ToString().Trim() + "',";
                sqlStr2 += "'" + (myds.Tables[0].Rows[i][9]).ToString().Trim() + "'";
                sqlStr2 += ")";
               
                try
                {
                    //框架中SQL执行的方式
                    bll.GetList1(sqlStr2);
                }
                catch (Exception ex)
                {
                    Response.Write("更新失败,失败原因:" + ex.Message);
                }
                
            }
            Response.Write("<script>alert('导入成功!请勿重复导入!');</script>");

        }
        public void bindGridView1()
        {
            
            try
            {
                getExcel();
                GridView1.DataBind();
                if (myds.Tables[0].Rows.Count != 0)
                {  
                    GridView1.DataBind();

                }
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.ToString() + "')</script>");
            }
        }
        //分页显示数据的绑定
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "if(window.oldtr==null||window.oldtr!=this){col=this.style.backgroundColor;this.style.backgroundColor='#95B8FF'}");
                e.Row.Attributes.Add("onmouseout", "if(window.oldtr==null||window.oldtr!=this){this.style.backgroundColor=col}");
                e.Row.Attributes.Add("onclick", "if(window.oldtr!=null){window.oldtr.style.backgroundColor=oldc;}this.style.backgroundColor='#e6c5fc';window.oldtr=this;oldc=col;");
            }
            if (e.Row.RowIndex != -1)
            {
                int indexID = this.GridView1.PageIndex * this.GridView1.PageSize + e.Row.RowIndex + 1;
                e.Row.Cells[0].Text = indexID.ToString();
            }
        }

        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            bindGridView1();
        }

        public override void VerifyRenderingInServerForm(Control control) { }
        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }

2,按列插入到数据库

因业务需求,需要对Excel表格中按列读取并更新到数据库中,这部分思路和插入差不多,也是循环读列然后更新到对应数据库的对应行。这部分本地测试时,想的比较复杂,代码写的很冗余,也是思考了很久,对此部分进行了精简更新。从数据库中动态查询列名对应的标识,然后在更新语句中使用。

其中,SQL语句拼接的问题,可以调试查看语句是否正确。

另外值得说明的就是,DataSet中读取select语句查询到的结果时,注意读取方式。这里就只是查询出记录对应的字段名,因此使用方式如下。

//sqlGetDw 为获取记录的字段名语句
DataSet dw = bll.GetList1(sqlGetDw);
//DataSet读取字段名称的方法
dw.Tables[0].Rows[0][0]).ToString()

具体代码如下。

 ///更新相应列需求数据
        protected void Button2_Click(object sender, EventArgs e)
        {
            getExcel();
            //获取单位名称,这个获取表头列的之前博客中写过
            string singleDw = GridView1.HeaderRow.Cells[10].Text.ToString();
            //从数据库的[wzglxt].[dbo].[zzjg]中查询  对应的编码
            
            for (int i = 0; i < myds.Tables[0].Rows.Count; i++)
            {
                string sqlGetDw = "select jgpxm from [wzglxt].[dbo].[zzjg] where jgmc = " + "'" + singleDw + "'";
                DataSet dw = bll.GetList1(sqlGetDw);
                string sqlStrUpdate = "update [wzglxt].[dbo].[jhmxb] set " + (dw.Tables[0].Rows[0][0]).ToString() + "=";
                sqlStrUpdate += "'" + (myds.Tables[0].Rows[i][10]).ToString().Trim() + "'";
                sqlStrUpdate += "where ID = " + "'" + (myds.Tables[0].Rows[i][0]).ToString().Trim() + "' and sj = " + "'" + (myds.Tables[0].Rows[i][1]).ToString().Trim() + "'";
                try
                {
                    bll.GetList1(sqlStrUpdate);
                }
                catch (Exception ex)
                {
                    Response.Write("更新失败,失败原因:" + ex.Message);
                }                
            }
            Response.Write("<script>alert('导入成功!请勿重复导入!');</script>");
        }

本人小白,也是刚接触ASP.net很多不懂的地方,欢迎大佬指点,一起努力冲冲冲!

Guess you like

Origin blog.csdn.net/weixin_40165004/article/details/120164025