导出excel不起作用 [英] Export to excel not working

查看:179
本文介绍了导出excel不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下网格视图:

I have a grid view like the following:

<form id="form21">
  <asp:GridView ID="GVcandidates" runat="server" AllowPaging="true" AllowSorting="True" AutoGenerateColumns="False" CssClass="tabLayout_Fixed" OnPageIndexChanging="GVcandidates_PageIndexChanging" OnRowCommand="GVcandidates_RowCommand" OnRowDataBound="GVcandidates_RowDataBound" OnSorting="GVcandidates_Sorting" PageSize="50" Width="100%">
</form>





我修改了页面标题如:



I modified the page header like:

EnableEventValidation="false"





按下按钮,我在后面的代码中写下以下内容:



And onclick of an button I write the following in code behind:

protected void exclexp_Click(object sender, EventArgs e)
{
   Response.ClearContent();
   Response.Buffer = true;
   Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
   Response.ContentType = "application/ms-excel";
   StringWriter sw = new StringWriter();
   HtmlTextWriter htw = new HtmlTextWriter(sw);
   GVcandidates.AllowPaging = false;
   //Change the Header Row back to white color
   GVcandidates.HeaderRow.Style.Add("background-color", "#FFFFFF");
   //Applying stlye to gridview header cells
   for (int i = 0; i < GVcandidates.HeaderRow.Cells.Count; i++)
   {
      GVcandidates.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
   }
   int j = 1;
   //This loop is used to apply stlye to cells based on particular row
   foreach (GridViewRow gvrow in GVcandidates.Rows)
   {
      //gvrow.BackColor = Color.White;
      if (j <= GVcandidates.Rows.Count)
      {
         if (j % 2 != 0)
         {
            for (int k = 0; k < gvrow.Cells.Count; k++)
            {
               gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
            }
         }
      }
      j++;
   }
   GVcandidates.RenderControl(htw);
   Response.Write(sw.ToString());
   Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
   /* Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time. */
}





当我点击按钮时没有发生任何事情,请帮助我很新asp.net



When I click the button nothing is happening, please help I am very new to asp.net

推荐答案

Excel文件格式不是HTML,因此您需要使用库来创建真正的Excel文件,例如http://epplus.codeplex.com/ [ ^ ]或者你应该创建一个你想要的html表示。
The Excel file format is not HTML, so you either need to use a library for creating true Excel files like http://epplus.codeplex.com/[^] or you should create a html representation of what you want.


使用此代码导出到excel gridview数据。确保将正确的数据源传递给dt(您可以提供与gridview相同的数据源)。



Use this code for export to excel gridview data. Make sure you pass correct datasource to dt(You can provide same datasource which you provide to gridview).

onbuttonclick()
{
datatable dt= new datatable();
dt= obj.getdataforexcel(); // here you can use datasource with which gridview is bind.
ExportToExcel(dt);
}

//export to excel function
  public void ExportToExcel(DataTable dt)
        {
            string XlsPath = "Sheet1";
            string attachment = string.Empty;
            HttpContext context = HttpContext.Current;
            if (XlsPath.IndexOf("\\") != -1)
            {
                string[] strFileName = XlsPath.Split(new char[] { '\\' });
                attachment = "attachment; filename=" + strFileName[strFileName.Length - 1] + ".xls";
            }
            else
                attachment = "attachment; filename=" + XlsPath + ".xls";
            try
            {
                context.Response.ClearContent();
                context.Response.AddHeader("content-disposition", attachment);
                context.Response.ContentType = "application/vnd.ms-excel";
               
                string tab = string.Empty;

                foreach (DataColumn datacol in dtRecords.Columns)
                {
                    context.Response.Write(tab + datacol.ColumnName);
                    tab = "\t";
                }
                context.Response.Write("\n");

                foreach (DataRow dr in dtRecords.Rows)
                {
                    tab = "";
                    for (int j = 0; j < dtRecords.Columns.Count; j++)
                    {
                        context.Response.Write(tab + Convert.ToString(dr[j]));
                        tab = "\t";
                    }

                    context.Response.Write("\n");
                }
                context.Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


参考这个

http://www.aspsnippets.com/forums/Articles/Export -GridView-to-Excel-in-ASPNet-with-Formatting-using-C-and-VBNet.aspx# [ ^ ]


这篇关于导出excel不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆