.net 将GridView导出到Excel而不丢失Excel中的网格线

.net 将GridView导出到Excel而不丢失Excel中的网格线,.net,asp.net,excel,gridview,export,.net,Asp.net,Excel,Gridview,Export,我有一个要导出到Excel的GridView。当我使用在线找到的示例代码时,它会将内容导出到Excel中,但出于某种原因,它也会清除导出表之外的所有网格线 对于一般的excel用户来说,这很容易修复,但我需要这个解决方案来为每个人工作 那么,有没有一种方法可以将GridView中的数据导出到Excel工作簿中,使其看起来像刚刚输入Excel?我已经在下面粘贴了我正在使用的代码,假设一个名为toPrint的GridView存在并且具有准确的数据 Response.Clear(); Response

我有一个要导出到Excel的GridView。当我使用在线找到的示例代码时,它会将内容导出到Excel中,但出于某种原因,它也会清除导出表之外的所有网格线

对于一般的excel用户来说,这很容易修复,但我需要这个解决方案来为每个人工作

那么,有没有一种方法可以将GridView中的数据导出到Excel工作簿中,使其看起来像刚刚输入Excel?我已经在下面粘贴了我正在使用的代码,假设一个名为toPrint的GridView存在并且具有准确的数据

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + name + "_Registration_Forms.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Page.EnableViewState = false;

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

toPrint.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());
Response.End();

编辑:找到一个部分解决方案。如果我以逗号分隔的列表形式导出,并将标题设置为CSV文件,它将正常打开,所有网格线(即使是导出数据之外的网格线)都会显示出来。当然,唯一的问题是在导出值之前必须从值中去掉所有逗号和换行符。

我过去使用过下面的helper函数。我只是给了用户一个复选框,他们可以选择是否包含网格线。显然,您可以将其更改为始终包含网格线

namespace Helpers
{
    public class GridViewExportUtil
    {
        public static void Export(string fileName, GridView gv, bool includeGridLines)
        {
           HttpContext.Current.Response.Clear();
           HttpContext.Current.Response.AddHeader(
               "content-disposition", string.Format("attachment; filename={0}", fileName));
           HttpContext.Current.Response.ContentType = "application/ms-excel";

           using (StringWriter sw = new StringWriter())
           {
               using (HtmlTextWriter htw = new HtmlTextWriter(sw))
               {
               //  Create a form to contain the grid
               Table table = new Table();

            if (includeGridLines)
            {
               table.GridLines = gv.GridLines;
            }

               //  add the header row to the table
               if (gv.HeaderRow != null)
               {
                   GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                   table.Rows.Add(gv.HeaderRow);
               }

               //  add each of the data rows to the table
               foreach (GridViewRow row in gv.Rows)
               {
                GridViewExportUtil.PrepareControlForExport(row);
                   table.Rows.Add(row);
               }

               //  add the footer row to the table
               if (gv.FooterRow != null)
               {
                   GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                   table.Rows.Add(gv.FooterRow);
               }

                  //  render the table into the htmlwriter
                  table.RenderControl(htw);

                  //  render the htmlwriter into the response
                  HttpContext.Current.Response.Write(sw.ToString());
                  HttpContext.Current.Response.End();
              }
           }
       }

        /// <summary>
        /// Replace any of the contained controls with literals
        /// </summary>
        /// <param name="control"></param>
       private static void PrepareControlForExport(Control control)
        {
           for (int i = 0; i < control.Controls.Count; i++)
           {
               Control current = control.Controls[i];
               if (current is LinkButton)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
               }
               else if (current is ImageButton)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
               }
               else if (current is HyperLink)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
               }
               else if (current is DropDownList)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
               }
               else if (current is CheckBox)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
               }

               if (current.HasControls())
               {
                GridViewExportUtil.PrepareControlForExport(current);
               }
           }
        }
    }
}

当我导出到Excel时,我也遇到了同样的问题,无法获取网格线


我解决这个问题的方法是将Gridlines=都放在标签内。

下面的帖子给了我答案。 我将总结如何处理代码

System.IO.StringWriter dvWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter OutputGenerator = new System.Web.UI.HtmlTextWriter(dvWriter);

            //To put in the excel gridlines 
            dvWriter.Write(@"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">");
            dvWriter.Write(@"<head>
                               <xml>
                                 <x:ExcelWorkbook> 
                                    <x:ExcelWorksheets>
                                       <x:ExcelWorksheet>
                                          <x:WorksheetOptions>
                                             <x:Panes></x:Panes>
                                             <x:Print><x:Gridlines /></x:Print>
                                          </x:WorksheetOptions>
                                        </x:ExcelWorksheet>
                                      </x:ExcelWorksheets>
                                    </x:ExcelWorkbook>
                                  </xml>
                                </head>");
//*******Put your Table Body here *******
VB

C


上面的方法输出了一个HTML格式的表格,Excel做得很好,几乎以完全相同的方式解析和显示。我不确定是否有解决方案,但如果格式不是那么重要,CSV输出可能是一个很好的选择。对于那些可能感兴趣的人,o.k.w的评论是我的方式。这并不完美,因为现在我必须从导出的内容中去掉逗号,但最终用户更喜欢这种方法。您可以尝试使用制表符而不是逗号来分隔值。我将此代码放在适当的位置,但它不起作用。现在什么也不导出,页面只是重新加载,就像按钮单击事件没有代码一样。而且,该代码处理在输出到excel的值网格中显示或不显示网格线。它对工作簿中的其余单元格没有任何影响。David Glass…很好的片段。是守门员!这仍然使excel中的其余网格线在数据之外保持空白
System.IO.StringWriter dvWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter OutputGenerator = new System.Web.UI.HtmlTextWriter(dvWriter);

            //To put in the excel gridlines 
            dvWriter.Write(@"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">");
            dvWriter.Write(@"<head>
                               <xml>
                                 <x:ExcelWorkbook> 
                                    <x:ExcelWorksheets>
                                       <x:ExcelWorksheet>
                                          <x:WorksheetOptions>
                                             <x:Panes></x:Panes>
                                             <x:Print><x:Gridlines /></x:Print>
                                          </x:WorksheetOptions>
                                        </x:ExcelWorksheet>
                                      </x:ExcelWorksheets>
                                    </x:ExcelWorkbook>
                                  </xml>
                                </head>");
//*******Put your Table Body here *******
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    'base.VerifyRenderingInServerForm(control);
'This remains empty
End Sub

Protected Sub btnExcel_Click(sender As Object, e As ImageClickEventArgs) Handles btnExcel.Click

    Response.Clear()
    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
    Response.Charset = ""
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.ContentType = "application/vnd.ms-excel"

    Dim stringWrite As New System.IO.StringWriter()
    Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)

    htmlWrite.Write("<html xmlns:o=""urn:schemas-microsoft-com:office:office"" ")
    htmlWrite.Write("xmlns:x=""urn:schemas-microsoft-com:office:excel"" ")
    htmlWrite.Write("xmlns=""http://www.w3.org/TR/REC-html40""> ")
    htmlWrite.Write("<head> ")
    htmlWrite.Write("<!--[if gte mso 9]><xml> ")
    htmlWrite.Write("<x:ExcelWorkbook> ")
    htmlWrite.Write("<x:ExcelWorksheets> ")
    htmlWrite.Write("<x:ExcelWorksheet> ")
    htmlWrite.Write("<x:Name>Sheet1</x:Name> ")
    htmlWrite.Write("<x:WorksheetOptions> ")
    htmlWrite.Write("<x:Selected/> ")
    htmlWrite.Write("<x:ProtectContents>False</x:ProtectContents> ")
    htmlWrite.Write("<x:ProtectObjects>False</x:ProtectObjects> ")
    htmlWrite.Write("<x:ProtectScenarios>False</x:ProtectScenarios> ")
    htmlWrite.Write("</x:WorksheetOptions> ")
    htmlWrite.Write("</x:ExcelWorksheet> ")
    htmlWrite.Write("</x:ExcelWorksheets> ")
    htmlWrite.Write("</x:ExcelWorkbook> ")
    htmlWrite.Write("</xml><![endif]--> ")
    htmlWrite.Write("</head>")
    htmlWrite.WriteLine("")

    gridView.HeaderStyle.Reset()
    gridView.FooterStyle.Reset()
    gridView.AlternatingRowStyle.Reset()
    gridView.RowStyle.Reset()

    gridView.BackColor = Color.Transparent
    gridView.GridLines = GridLines.None
    gridView.RenderControl(htmlWrite)

    Response.Write(stringWrite.ToString())
    Response.[End]()
End Sub
public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
    //This remains empty
}


protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.ms-excel";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

    htmlWrite.Write("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
    htmlWrite.Write("xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
    htmlWrite.Write("xmlns=\"http://www.w3.org/TR/REC-html40\"> ");
    htmlWrite.Write("<head> ");
    htmlWrite.Write("<!--[if gte mso 9]><xml> ");
    htmlWrite.Write("<x:ExcelWorkbook> ");
    htmlWrite.Write("<x:ExcelWorksheets> ");
    htmlWrite.Write("<x:ExcelWorksheet> ");
    htmlWrite.Write("<x:Name>Sheet1</x:Name> ");
    htmlWrite.Write("<x:WorksheetOptions> ");
    htmlWrite.Write("<x:Selected/> ");
    htmlWrite.Write("<x:ProtectContents>False</x:ProtectContents> ");
    htmlWrite.Write("<x:ProtectObjects>False</x:ProtectObjects> ");
    htmlWrite.Write("<x:ProtectScenarios>False</x:ProtectScenarios> ");
    htmlWrite.Write("</x:WorksheetOptions> ");
    htmlWrite.Write("</x:ExcelWorksheet> ");
    htmlWrite.Write("</x:ExcelWorksheets> ");
    htmlWrite.Write("</x:ExcelWorkbook> ");
    htmlWrite.Write("</xml><![endif]--> ");
    htmlWrite.Write("</head>");
    htmlWrite.WriteLine("");

    gridView.HeaderStyle.Reset();
    gridView.FooterStyle.Reset();
    gridView.AlternatingRowStyle.Reset();
    gridView.RowStyle.Reset();

    gridView.BackColor = Color.Transparent;
    gridView.GridLines = GridLines.None;
    gridView.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());
    Response.End();

}