Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在asp.net中将网格视图导出到excel时,未刷新网格视图_C#_Asp.net - Fatal编程技术网

C# 在asp.net中将网格视图导出到excel时,未刷新网格视图

C# 在asp.net中将网格视图导出到excel时,未刷新网格视图,c#,asp.net,C#,Asp.net,我想到了这样一个场景:当将网格视图导出到excel时,它不会刷新我的网格数据源。下面是我以前做过的代码。下面的代码正在更新数据库中的标志,然后尝试在Fill grid方法中刷新网格数据源 protected void Process_Command(object sender, CommandEventArgs e) { if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))

我想到了这样一个场景:当将网格视图导出到excel时,它不会刷新我的网格数据源。下面是我以前做过的代码。下面的代码正在更新数据库中的标志,然后尝试在Fill grid方法中刷新网格数据源

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)
{

}
public void ExportToExcel(Int64 OGPCode)
{
DataTable dtPickList=GeneralQuery.GetDocumentPickList(OGPCode);
if(dtPickList!=null&&dtPickList.Rows.Count>0)
{
//创建虚拟网格视图
GridView GridView1=新的GridView();
GridView1.AllowPaging=false;
GridView1.DataSource=dtPickList;
GridView1.DataBind();
Response.Clear();
Response.Buffer=true;
AddHeader(“内容处置”、“附件;文件名=Inbox.xls”);
响应。Charset=“”;
Response.ContentType=“application/vnd.ms excel”;
StringWriter sw=新的StringWriter();
HtmlTextWriter hw=新的HtmlTextWriter(sw);
对于(int i=0;i

请帮帮我,我做错了什么。谢谢

当您动态更新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();

}

最后,我找到了在将网格视图导出到excel时刷新网格视图的方法。我只需创建新的web表单并将
ExportGridToExcel()
方法放入
Page\u 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文件web表单及其实现

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();
        }
    }
公共部分类下载Excel:System.Web.UI.Page
{
受保护的无效页面加载(对象发送方、事件参数e)
{
如果(!Page.IsPostBack)
{
if(!string.IsNullOrEmpty(Convert.ToString(Session[“OGPCode”]))
{
ExportToExcel(转换为64(会话[“OGPCode]”);
会话[“OGPCode”]=null;
}
}
}
公共无效ExportToExcel(Int64 OGPCode)
{
DataTable dt=GeneralQuery.GetDocumentPickList(OGPCode);
//创建一个新的字节数组
字节[]bin;
string FileName=“拾取列表-”+DateTime.Now.ToString();
//创建新的excel文档
使用(ExcelPackage ExcelPackage=new ExcelPackage())
{
//创建新工作表
Excel工作表ws=excelPackage.工作簿.Worksheets.Add(文件名);
//将数据表的内容添加到excel文件中
ws.Cells[“A1”].LoadFromDataTable(dt,true);
//自动修复列
ws.Cells[ws.Dimension.Address].AutoFitColumns();
//循环所有列

对于(int col=1;col导出后是否要清空gridview?否。我想刷新网格数据源开始使用专门的库来创建Excel文件,如.and。您现在所做的只是创建一个扩展名为.xls的HTML页面。@VDWWD我遵循示例,网格视图正在导出到Excel,但仍然无法刷新网格数据将网格视图导出到excel时创建一个源。您不能这样做。要么导出文件,要么更新UI,不能同时更新两者。不要使用StringWriter将excel文件创建为html。这将导致各种问题。