在asp.net中将网格视图导出为Excel时,网格视图未刷新

时间:2019-01-14 06:11:40

标签: c# asp.net

我想出了一个方案,即在导出网格视图以使其不刷新其网格数据源时表现出色。以下是我以前做过的代码。下面的代码是更新数据库中的标志,然后尝试使用“填充网格”方法刷新网格数据源。

protected void Process_Command(object sender, CommandEventArgs e)
        {
            if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
            {

                using (var transaction = context.Database.BeginTransaction())
                {
                    DocumentOGP objDocumentOGP = context.DocumentOGPs.Find(Convert.ToInt64(e.CommandArgument));

                    objDocumentOGP.UpdationDate = DateTime.Now;
                    objDocumentOGP.DispatchStatusID = 2;
                    context.DocumentOGPs.Add(objDocumentOGP);
                    context.Entry(objDocumentOGP).State = System.Data.Entity.EntityState.Modified;
                    context.SaveChanges();
                    transaction.Commit();
                    FillGrid();

                }
                ExportToExcel(Convert.ToInt64(e.CommandArgument));
            }
        } 

下面是“导出到excel”方法。

public void ExportToExcel(Int64 OGPCode)
        {

            DataTable dtPickList =GeneralQuery.GetDocumentPickList(OGPCode);
            if (dtPickList != null && dtPickList.Rows.Count>0)
            {
                //Create a dummy GridView
                GridView GridView1 = new GridView();
                GridView1.AllowPaging = false;
                GridView1.DataSource = dtPickList;
                GridView1.DataBind();

                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=Inbox.xls");
                Response.Charset = "";
                Response.ContentType = "application/vnd.ms-excel";
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);

                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    //Apply text style to each Row
                    GridView1.Rows[i].Attributes.Add("class", "textmode");
                }
                GridView1.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
                GridView1.DataSource = null;
                Response.Write(Request.RawUrl.ToString());
            }
        }



public override void VerifyRenderingInServerForm(Control control)
{

}

请帮助我我做错了。谢谢

2 个答案:

答案 0 :(得分:0)

最后,我找到了将网格视图导出到excel时刷新网格视图的方法。我只是创建新的Web表单并将ExportGridToExcel()方法放在Page_Load中,然后单击按钮刷新网格视图数据源并打开新选项卡以下载excel文件。下面是我的代码。

protected void Process_Command(object sender, CommandEventArgs e)
        {
            if (Session["Status"] != "Refreshed")
            {
                if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
                {

                    using (var transaction = context.Database.BeginTransaction())
                    {
                        DocumentOGP objDocumentOGP = context.DocumentOGPs.Find(Convert.ToInt64(e.CommandArgument));

                        objDocumentOGP.UpdationDate = DateTime.Now;
                        objDocumentOGP.DispatchStatusID = 2;
                        context.DocumentOGPs.Add(objDocumentOGP);
                        context.Entry(objDocumentOGP).State = System.Data.Entity.EntityState.Modified;
                        context.SaveChanges();
                        transaction.Commit();
                        FillGrid();
                        Session["OGPCode"] = Convert.ToString(e.CommandArgument);

                    }

                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "OpenWindow", "window.open('http://localhost:56430/DownLoadExcel','_newtab');", true);
                }
            }
        } 

下面是我的下载excel文件网络表单及其实现

public partial class DownLoadExcel : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(Convert.ToString(Session["OGPCode"])))
                {
                    ExportToExcel(Convert.ToInt64(Session["OGPCode"]));
                    Session["OGPCode"] = null;
                }
            }
        }
        public void ExportToExcel(Int64 OGPCode)
        {
            DataTable dt = GeneralQuery.GetDocumentPickList(OGPCode);
            //create a new byte array       
            byte[] bin;
            string FileName = "Pick-List-" + DateTime.Now.ToString();
            //create a new excel document
            using (ExcelPackage excelPackage = new ExcelPackage())
            {
                //create a new worksheet
                ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add(FileName);

                //add the contents of the datatable to the excel file
                ws.Cells["A1"].LoadFromDataTable(dt, true);

                //auto fix the columns
                ws.Cells[ws.Dimension.Address].AutoFitColumns();

                //loop all the columns
                for (int col = 1; col <= ws.Dimension.End.Column; col++)
                {
                    //make all columns just a bit wider, it would sometimes not fit
                    ws.Column(col).Width = ws.Column(col).Width + 1;

                    var cell = ws.Cells[1, col];

                    //make the text bold
                    cell.Style.Font.Bold = true;

                    //make the background of the cell gray
                    var fill = cell.Style.Fill;
                    fill.PatternType = ExcelFillStyle.Solid;
                    fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));

                    //make the header text upper case
                    cell.Value = ((string)cell.Value).ToUpper();
                }

                //convert the excel package to a byte array
                bin = excelPackage.GetAsByteArray();
            }

            //clear the buffer stream
            Response.ClearHeaders();
            Response.Clear();
            Response.Buffer = true;

            //set the correct contenttype
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            //set the correct length of the data being send
            Response.AddHeader("content-length", bin.Length.ToString());

            //set the filename for the excel package
            Response.AddHeader("content-disposition", "attachment; filename=\"" + FileName + ".xlsx\"");

            //send the byte array to the browser
            Response.OutputStream.Write(bin, 0, bin.Length);

            //cleanup
            Response.Flush();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
    }

答案 1 :(得分:-1)

动态更新GridView或任何控件值时,应呈现并导出到其他应用程序。

示例:使用GridView的RenderControl方法进行检查。

private void ExportGridToExcel()
{
    Response.Clear();
    Response.Buffer = true;
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Charset = "";
    string FileName = "xyz.xls";
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
    GridView1.RenderControl(htmltextwrtter);
    Response.Write(strwritter.ToString());
    Response.End();

}