2010-03-04 136 views
4

我有一個要導出到Excel的GridView。當我使用我在網上找到的示例代碼時,它會將內容導出到Excel中,但出於某種原因,它還會清除所導出表格外的所有網格線。導出GridView到Excel而不會丟失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文件,則它會正常打開,並顯示所有網格線(即使是導出數據以外的網格線)。當然,唯一的問題是,在導出它們之前,必須從我的值中去掉每個逗號和換行符。

+1

上述方法輸出一個Excel中進行 '出色' 來解析和顯示在幾乎精確複製一個HTML格式化的表格。我不確定是否有解決方案,但如果格式不重要,CSV輸出可能是一個不錯的選擇。 – 2010-03-04 01:19:55

+0

給那些可能感興趣的人,o.k.w的評論是我去的方式。這並不完美,因爲現在我不得不從我輸出的內容中去掉逗號,但最終用戶更喜歡這種方法。 – 2010-04-27 14:10:41

+0

您可以嘗試使用製表符而不是逗號來分隔值 – mslliviu 2012-01-22 08:46:42

回答

3

我已經使用了以下的幫助函數。我只給了用戶一個複選框,他們可以選擇是否包含網格線。顯然,你可以改變這個始終包含網格線。

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

我將此代碼放置到位,但它不起作用。現在沒有任何輸出,頁面只是重新加載,就像按鈕點擊事件沒有代碼一樣。 – 2010-03-04 18:31:41

+0

此外,該代碼處理顯示或不顯示輸出爲excel的值網格中的網格線。它對工作簿中的其他單元沒有任何作用。 – 2010-03-04 19:42:28

+0

大衛玻璃...不錯的片段。這是一個守護者! – s15199d 2012-07-11 14:56:34

3

我有同樣的問題沒有得到網格線時,我導出到Excel。

我解決它的方法是將Gridlines="Both"放在<datagrid>標籤內。

+0

這仍然使excel中的其餘網格線(數據外)留空 – rDroid 2014-11-14 09:49:07

5

以下的帖子給了我答案。 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 ******* 
0

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

}