2012-09-21 72 views
0

我有下面的代碼用於導出到excel的gridview。我將GridView行添加到System.Web.UI.WebControls.Table中。現在,我需要將背景顏色應用於導出的Excel中的標題和數據行(有兩個標題行)。導出到Excel的TableRow樣式

我累了以下。它沒有提供期望的結果。當前解決方案的

問題

  1. 一個標題行不具有背景顏色
  2. 着色施加於不具有數據單元(單元「H」,「I」,等)

我們該如何糾正它?

enter image description here

注:我想學習導出功能。所以,請不要建議使用任何第三方控件。我只是探索這種方法的所有功能。

我使用以下代碼將標題分組添加到原始gridview。

protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Header) 
    { 
     System.Text.StringBuilder sbNewHeader = new StringBuilder(); 
     sbNewHeader.AppendFormat("&nbsp;</th>" + 
      "<th colspan='2' class='tableColGroupAssociate'>Associate Info <a href='#' class='associateHide'> Hide </a> </th>" + 
      "<th colspan='2' class='tableColGroupTransaction'>Financial Info <a href='#' class='financialHide'> Hide </a> </th>" + 
      "<th colspan='2' class='tableColGroupDailyTax'>Tax Info <a href='#' class='dailyTaxHide'> Hide </a> </th>" 
      + "</tr>"); 
     sbNewHeader.AppendFormat("<tr class='{0}'><th>{1}", this.gvCustomers.HeaderStyle.CssClass, e.Row.Cells[0].Text); 
     e.Row.Cells[0].Text = sbNewHeader.ToString(); 
    } 
} 

完整代碼

public static void Export(GridView gv) 
{ 
    HttpContext.Current.Response.Clear(); 
    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyExcelFile.xls")); 
    HttpContext.Current.Response.ContentType = "application/ms-excel"; 

    using (StringWriter stringWriter = new StringWriter()) 
    { 
     using (HtmlTextWriter tetxWriter = new HtmlTextWriter(stringWriter)) 
     { 

      System.Web.UI.WebControls.Table tableControl = new Table(); 
      tableControl.GridLines = gv.GridLines; 

      //Before the next step - we can remove any controls inside the gridview and replace with literal control 

      // Add the header row to the table 
      if (gv.HeaderRow != null) 
      { 
       TableRow tableRow = gv.HeaderRow; 
       tableRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange"; 
       tableControl.Rows.Add(gv.HeaderRow); 
      } 

      // Add each of the data rows to the table 
      foreach (GridViewRow row in gv.Rows) 
      { 
       TableRow tableRow = row; 
       tableRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Yellow"; 
       tableControl.Rows.Add(row); 
      } 


      // Render the table into the htmlwriter 
      tableControl.RenderControl(tetxWriter); 

      // Render the htmlwriter into the response 
      HttpContext.Current.Response.Write(stringWriter.ToString()); 
      HttpContext.Current.Response.End(); 


     } 
    } 
} 

編輯

基於從ANKIT評論,我嘗試以下;結果仍不如預期。

  if (gv.HeaderRow != null) 
      { 
       TableRow tableRow = gv.HeaderRow; 

       foreach (TableCell cell in tableRow.Cells) 
       { 
        cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange"; 
       } 
       tableControl.Rows.Add(gv.HeaderRow); 
      } 

enter image description here


+1

什麼,我得到的是您正在複製整行gridView並將其粘貼到Excel行中。我有你的問題的解決方法,但不建議這樣做,因爲你將使用不必要的嵌套循環只是爲了格式化,如果你覺得它沒問題,那麼你可以使用一個循環的循環內的列循環行,然後你會一次爲每個單元格添加值而不是一行,那麼gridView區域外的單元格將不會獲取顏色。 – Ankit

+0

@Ankit謝謝。我嘗試了你的建議。仍然存在問題,如更新後的問題所示。有什麼建議麼? – Lijo

+0

請問您,請逐步調試流程以瞭解實際發生的情況。 – Ankit

回答

0

我想出了一個辦法......對於其他人的利益,我將它張貼在這裏:

參考文獻:

  1. ASP.NET Excel export encoding problem

enter image description here

其他注意事項:當一個新的表被創建TableSection可以用來定義標題

newRow.TableSection = TableRowSection.TableHeader; 

CODE

//改變用於添加動態標題爲HTML渲染邏輯:

protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e) 
{ 

    if (e.Row.RowType == DataControlRowType.Header) 
    { 
     GridViewRow newHeaderRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal); 

     TableCell cell1 = new TableHeaderCell(); 
     cell1.ColumnSpan = 1; //e.Row.Cells.Count; 
     cell1.Text = ""; 

     TableCell cell2 = new TableCell(); 
     cell2.ColumnSpan = 2; 
     cell2.Text = "One"; 

     TableCell cell3 = new TableCell(); 
     cell3.ColumnSpan = 2; 
     cell3.Text = "Two"; 

     TableCell cell4 = new TableCell(); 
     cell4.ColumnSpan = 2; 
     cell4.Text = "Three"; 

     newHeaderRow.Cells.Add(cell1); 
     newHeaderRow.Cells.Add(cell2); 
     newHeaderRow.Cells.Add(cell3); 
     newHeaderRow.Cells.Add(cell4); 

     ((GridView)sender).Controls[0].Controls.AddAt(0, newHeaderRow); 
    } 

    if (e.Row.RowType == DataControlRowType.Header) 
    { 

     //System.Text.StringBuilder sbNewHeader = new StringBuilder(); 
     //sbNewHeader.AppendFormat("&nbsp;</th>" + 
     // "<th colspan='2' class='tableColGroupAssociate'>Associate Info <a href='#' class='associateHide'> Hide </a> </th>" + 
     // "<th colspan='2' class='tableColGroupTransaction'>Financial Info <a href='#' class='financialHide'> Hide </a> </th>" + 
     // "<th colspan='2' class='tableColGroupDailyTax'>Tax Info <a href='#' class='dailyTaxHide'> Hide </a> </th>" 
     // + "</tr>"); 
     //sbNewHeader.AppendFormat("<tr class='{0}'><th>{1}", this.gvCustomers.HeaderStyle.CssClass, e.Row.Cells[0].Text); 
     //e.Row.Cells[0].Text = sbNewHeader.ToString(); 


    } 

} 

//匯出邏輯 - 應用類似的邏輯再次

public static void Export(GridView gv) 
{ 
    HttpContext.Current.Response.Clear(); 
    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyExcelFile.xls")); 
    HttpContext.Current.Response.ContentType = "application/ms-excel"; 


    //Response.ContentEncoding = System.Text.Encoding.Unicode; 
    //Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); 


    using (StringWriter stringWriter = new StringWriter()) 
    { 
     using (HtmlTextWriter tetxWriter = new HtmlTextWriter(stringWriter)) 
     { 

      System.Web.UI.WebControls.Table tableControl = new Table(); 
      tableControl.GridLines = gv.GridLines; 

      // Add the header row to the table 
      if (gv.HeaderRow != null) 
      { 
       ReplaceControlForExport(gv.HeaderRow); 


       #region Dynamic Frrst Header Row 

       TableRow newRow = new TableRow(); 

       TableCell cell1 = new TableHeaderCell(); 
       cell1.ColumnSpan = 1; 
       cell1.Text = ""; 

       TableCell cell2 = new TableCell(); 
       cell2.ColumnSpan = 2; 
       cell2.Text = "One"; 

       TableCell cell3 = new TableCell(); 
       cell3.ColumnSpan = 2; 
       cell3.Text = "Two"; 

       TableCell cell4 = new TableCell(); 
       cell4.ColumnSpan = 2; 
       cell4.Text = "Three"; 

       newRow.Cells.Add(cell1); 
       newRow.Cells.Add(cell2); 
       newRow.Cells.Add(cell3); 
       newRow.Cells.Add(cell4); 

       foreach (TableCell cell in newRow.Cells) 
       { 
        cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Purple"; 
       } 
       tableControl.Rows.Add(newRow); 

       #endregion 

       TableRow originalHeaderRow = gv.HeaderRow; 
       foreach (TableCell cell in originalHeaderRow.Cells) 
       { 
        cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange"; 
       } 
       tableControl.Rows.Add(originalHeaderRow); 
      } 


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

       TableRow tableRow = row; 
       foreach (TableCell cell in tableRow.Cells) 
       { 
        cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Yellow"; 
       } 
       tableControl.Rows.Add(row); 
      } 


      // Render the table into the htmlwriter 
      tableControl.RenderControl(tetxWriter); 

      // Render the htmlwriter into the response 
      HttpContext.Current.Response.Write(stringWriter.ToString()); 
      HttpContext.Current.Response.End(); 


     } 
    } 
    } 

private static void ReplaceControlForExport(Control mainControlElement) 
{ 
    for (int i = 0; i < mainControlElement.Controls.Count; i++) 
    { 
     Control currentControl = mainControlElement.Controls[i]; 

     if (currentControl is LinkButton) 
     { 
      mainControlElement.Controls.Remove(currentControl); 
      mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as LinkButton).Text)); 
     } 
     else if (currentControl is ImageButton) 
     { 
      mainControlElement.Controls.Remove(currentControl); 
      mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as ImageButton).AlternateText)); 
     } 
     else if (currentControl is HyperLink) 
     { 
      mainControlElement.Controls.Remove(currentControl); 
      mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as HyperLink).Text)); 
     } 
     else if (currentControl is DropDownList) 
     { 
      mainControlElement.Controls.Remove(currentControl); 
      mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as DropDownList).SelectedItem.Text)); 
     } 
     else if (currentControl is CheckBox) 
     { 
      mainControlElement.Controls.Remove(currentControl); 
      mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as CheckBox).Checked ? "True" : "False")); 
     } 

     //Recursive Call 
     if (currentControl.HasControls()) 
     { 
      ReplaceControlForExport(currentControl); 
     } 
    } 
} 
1

如果你想在你的Excel文件寫得怎樣來看看ClosedXML

添加表格更多的控制很簡單,只要

var wb = new XLWorkbook(); 
wb.Worksheets.Add(myDataTable); 
wb.SaveAs("MySheet.xlsx"); 

使用API​​,你可以這樣編碼:

var rngTable = ws.Range("B2:F6"); 
rngTable.FirstCell().Style 
    .Font.SetBold() 
    .Fill.SetBackgroundColor(XLColor.CornflowerBlue) 
    .Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center); 
+0

寫出html,並讓excel弄清楚如何顯示它永遠不會讓你完全控制輸出。我總是喜歡這個'RenderControl'方法。 – nunespascal