Экспорт GridView в Excel без потери линий сетки в Excel - PullRequest
4 голосов
/ 04 марта 2010

У меня есть GridView, который я хочу экспортировать в Excel. Когда я использую пример кода, который я нахожу в Интернете, он прекрасно экспортирует содержимое в Excel, но по некоторым причинам он также очищает все линии сетки за пределами моей экспортированной таблицы.

Для вашего обычного пользователя excel это достаточно легко исправить, но мне нужно, чтобы это решение работало для всех.

Итак, есть ли способ экспортировать данные из GridView в книгу Excel, чтобы они выглядели так, как будто они были напечатаны в Excel? Я вставил код, который я использую ниже, предположим, что GridView с именем toPrint существует и содержит точные данные.

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-файлом, он открывается нормально, и отображаются все линии сетки (даже те, которые находятся вне экспортируемых данных). Конечно, единственная проблема в этом состоит в том, чтобы вычеркнуть все запятые и символы новой строки из моих значений перед их экспортом.

Ответы [ 4 ]

5 голосов
/ 10 октября 2013

Следующий пост дал мне ответ. http://forums.asp.net/t/1074110.aspx Я подведу итог, что делать с кодом.

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 *******
3 голосов
/ 24 мая 2012

У меня была такая же проблема, когда я не получал линии сетки при экспорте в Excel.

Я решил это, поместив Gridlines="Both" в тег <datagrid>.

3 голосов
/ 04 марта 2010

В прошлом я использовал вспомогательную функцию ниже. Я просто дал пользователю флажок, который он мог выбрать, чтобы включить линии сетки или нет. Очевидно, вы можете изменить это, чтобы всегда включать линии сетки.

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);
               }
           }
        }
    }
}

Это пример того, как вы бы назвали это:

GridViewExportUtil.Export("QueryResults.xls", GridView1, includeGridLines);
0 голосов
/ 27 августа 2015

VB

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

C #

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();

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...