现在的位置: 首页 > 综合 > 正文

C#中将控件数据导出Excel

2018年01月23日 ⁄ 综合 ⁄ 共 5524字 ⁄ 字号 评论关闭

在asp.net项目中的一个把数据 导出Excel表格的小事件如下:

 protected void ibnOut_Click(object sender, ImageClickEventArgs e)//导出Excel按钮的点击事件
        {
              GridView2.DataSource = dt;//dt是查询出的结果集

                GridView2.DataBind();
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "UTF-8";
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment;filename=/"" + HttpUtility.UrlEncode ("FileName.xls", System.Text.Encoding.UTF8) + "/"");
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.HeaderEncoding = System.Text.Encoding.UTF8;

                Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
                GridView2.Visible = true;//设置成true才能显示写出 标记A
                System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
                this.GridView2.RenderControl(oHtmlTextWriter);
                Response.Output.Write(oStringWriter.ToString());
                Response.Flush();
                Response.End();
                GridView2.Visible = false;//不让控件在前台显示

                //如果控件使用的是前台显示的控件 并且分页 那么我们可以在标记A处设置成不分页 然后在最后在还原成分页状态

        }

 

之后一定要重写方法:

 public override void VerifyRenderingInServerForm(Control control)
        {
           // base.VerifyRenderingInServerForm(control);
        }

 

asp.net中,读取导入的Excel文件 插入操作:

  protected void btnDaoru_Click(object sender, EventArgs e)
        {
            lblshowmessage.Text = "";
            if (FileUploadExcel.HasFile)
            {
                string fileException = System.IO.Path.GetExtension(FileUploadExcel.FileName).ToLower(); //获取扩展名
                if (fileException == ".xls")
                {
                    string fileName = System.IO.Path.GetFileName(FileUploadExcel.FileName);
                    string serverPath = Server.MapPath("~/Upload/board.xls");//获取完整上传路径
                    FileUploadExcel.PostedFile.SaveAs(serverPath);//文件上传到服务器

                    OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + serverPath + ";Extended Properties=Excel 8.0;");//连接串
                    string cmdTxt = "Select * from [Sheet1$]";
                    OleDbCommand cmd = new OleDbCommand(cmdTxt, conn);
                    try
                    {
                        conn.Open();
                        IDataReader r = cmd.ExecuteReader();
                        int success = 0;
                        int failed = 0;
                        int count = 0;
                        while (r.Read())
                        {
                            count++;
                            try
                            {
                                BFlowChart c = new BFlowChart();
                                Share s = new Share();
                                c.BoardState = "完好";
                                c.BxOrFb = "保修";
                                c.Imei = Convert.ToString(r[0]);
                                c.InputTime = DateTime.Now;
                                c.ListNO = "KFRK";
                                c.ListSort = "保修库房入库";
                                c.Mobile = Share.GetMobileTypeByImei(Convert.ToString(r[0]));
                                c.Remark = txtRemark.Text;
                                c.ReseveUserID = "bxkf";
                                c.ReseveName = "保修库房";
                                c.Source = ddlSourceType.SelectedValue;
                                c.UserID = lblloginUserId.Text;
                                c.UserName = lblloginUserName.Text;
                                if (service.ExistAndNotOut(c.Imei))
                                {
                                    lblshowmessage.Text += "【" + count + "】导入失败,imei已存在于系统<br />";
                                    continue;
                                }
                                if (null == c.Imei || c.Imei.Length == 0)
                                {
                                    lblshowmessage.Text += "【" + count + "】导入失败,imei为空<br />";
                                    continue;
                                }
                                if (c.Imei.Length != 15)
                                {
                                    lblshowmessage.Text += "【" + count + "】" + c.Imei + "IMEI不是15位<br />";
                                }
                                if (c.Mobile == "")
                                {
                                    lblshowmessage.Text += "【" + count + "】" + c.Imei + "没有成功得到机型<br />";
                                }
                                service.BoardSaoru(c);
                                success++;
                            }
                            catch (Exception ex)
                            {
                                failed++;
                                //message += "/>【" + count + "】" + ex.Message + "<br />";
                                lblshowmessage.Text += "【" + count + "】" + ex.Message + "<br />";
                            }

                        }

                        r.Close();
                        BindGridView();
                        lblshowmessage.Text += "成功导入数据" + success + "条";
                    }
                    finally
                    {
                        conn.Close();
                        System.IO.File.Delete(serverPath);
                    }

                }
                else
                {
                    lblshowScript.Text = "<script>alert('导入文件的格式需要.xls 文件');</script>";
                }
            }
            else
            {
                lblshowScript.Text = "<script>alert('请选择需要导入的.xls文件');</script>";

            }

        }

 

 

抱歉!评论已关闭.