ASP.Net 实现Excel数据到GridView,再到SQL Server的转换

需求分析:想要实现B/S模式下在线编辑Excel表数据并提交保存在数据库中。然而经过调研,ASP.Net对于B/S模式下,并不能实现调用本地程序实现编辑Excel的功能。想实现类似的功能,有pageoffice等第三方付费插件,因此结合相关部门人员对需求进行了二次评估,转变思路,不再进行在线编辑Excel的功能模块,从而转变成导入导出Excel文件,用户还是对Excel文件进行操作,最终数据仍然是到数据库中统计汇总。

主要实现功能及步骤

1)实现Excel数据导入到GridView中

2)实现GridView导入到SQL Server中

3)实现SQL Server导出到Excel中

1.实现Excel数据导入到GridView中

ASP页面布局如上图所示,因为是测试主要功能,并没有进行页面格式的美化。

代码如下:

<form id="form1" runat="server">
        <div >
         <table border="1" bordercolor="#bed0cd" cellpadding="0" cellspacing="0">
                <tr>
                    <td style="font-weight: bold; font-size: 11pt; text-align: center">
                        将Excel中数据读入到GridView中</td>
                </tr>            
                <tr>
                    <td style="text-align: center">
                        <asp:Button ID="Button1" runat="server" Font-Size="9pt" OnClick="Button1_Click" Text="读入Excel" style="border-left-color: #3333ff; border-bottom-color: #3333ff; border-top-style: inset; border-top-color: #3333ff; border-right-style: inset; border-left-style: inset; border-right-color: #3333ff; border-bottom-style: inset"/></td>
                    <td style="text-align: center">
                        <asp:Button ID="Button2" runat="server" Font-Size="9pt" OnClick="Button2_Click" Text="导入数据库" style="border-left-color: #3333ff; border-bottom-color: #3333ff; border-top-style: inset; border-top-color: #3333ff; border-right-style: inset; border-left-style: inset; border-right-color: #3333ff; border-bottom-style: inset"/></td>
                </tr>
                 <tr>
                      <asp:GridView ID="GridView1" runat="server">
                            </asp:GridView>
     
                 </tr>
            </table>
        </div>
   </form> 

 逻辑功能实现代码:

protected void Button1_Click(object sender, EventArgs e)
        {
            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);
            DataSet myds = new DataSet();
            myda.Fill(myds);
            GridView1.DataSource = myds;
            GridView1.DataBind();
           
        }

实现结果:

2.实现GridView导入到SQL Server中

前台页面代码如上,功能逻辑代码如下:

protected void Button2_Click(object sender, EventArgs e)
        {
            
             for (int i = 0; i < GridView1.Rows.Count; i++)
             {

                 string sqlStr2 = "insert into [wzgl].[dbo].[TestSql]([wid],[lb],[wlbm],[wlmc],[jldw],[dj],[sl],[zj],[bz])values";
                 sqlStr2 += "('"  + (GridView1.Rows[i].Cells[0]).Text.ToString().Trim()+ "',";
                 sqlStr2 += "'" + (GridView1.Rows[i].Cells[1]).Text.ToString().Trim()+ "',";
                 sqlStr2 += "'" + (GridView1.Rows[i].Cells[2]).Text.ToString().Trim() + "',";
                 sqlStr2 += "'" + (GridView1.Rows[i].Cells[3]).Text.ToString().Trim()+ "',";
                 sqlStr2 += "'" + (GridView1.Rows[i].Cells[4]).Text.ToString().Trim() + "',";
                 sqlStr2 += "'" + (GridView1.Rows[i].Cells[5]).Text.ToString().Trim()+ "',";
                 sqlStr2 += "'" + (GridView1.Rows[i].Cells[6]).Text.ToString().Trim() + "',";
                 sqlStr2 += "'" + (GridView1.Rows[i].Cells[7]).Text.ToString().Trim() + "',";
                 sqlStr2 += "'" + (GridView1.Rows[i].Cells[8]).Text.ToString().Trim()+ "'" ;
                 sqlStr2 += ")";
                 string strConnection = ConfigurationManager.ConnectionStrings["wzglConnectionString"].ConnectionString;
                 SqlConnection 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();
                  }
               }
             Response.Write("<script>alert('导入成功!请勿重复导入!');</script>");
             
        }

说明:循环读取GridView内数据再做数据插入操作。因为之前对.net并不熟悉,取GridView数据着实下了点功夫,看很多都是转换成数据集或者DataTable形式,放到程序中调试了很久一直是空数据集。经过查阅资料以及请教大神,总算明白了GridView行和列如何取。

GridView.Rows[i].Cells[j]
//表示表格中第i+1行  第j+1列的数据

GridView.Rows.Count
//表示表格中拥有的行数

取出行列数据后进行sql语言的编写再循环插入数据库就可以了。

如果出现:更新失败,失败原因:将截断字符串或二进制数据。 语句已终止。

愿意及解决办法:是因为所填写的数据超出数据库字段所规定的长度。将字段设置成text类型或者在原基础上将字段设置在允许的字段范围之上就可以了。

实现结果:

3.实现SQL Server导出到Excel中

 ASP前台页面如上图。

逻辑功能代码

 protected void Button2_Click(object sender, EventArgs e)
        {
            Export("application/ms-excel", "testExport.xls");
        }
        private void Export(string FileType, string FileName)
        {
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
            Response.ContentType = FileType;
            this.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            GridView1.RenderControl(hw);
            Response.Write(tw.ToString());
            Response.End();
        }
        private void bind()
        {
            string jslb = string.Format("select * from [wzgl].[dbo].[TestImport]");
            DataSet myds = new DataSet();
            GridView1.DataSource = myds;
            GridView1.DataBind();
        
        }

实现结果:

本人程序小白一枚,欢迎各位大佬批评指正。需交流可以留言,看到第一时间回复,一起冲冲冲!

查阅参考:

1,GridView控件说明

2,ASP.Net菜鸟教程

Guess you like

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