I'm using the below code to export the gridview to excel. When I export the contents are appearing fine with no problems, but I am getting a control label like System.WebControls.UI.Style this in my first cell in A1 cell.
Is there a way to hide this or remove and below is my code.
CS:
protected void Unnamed1_Click(object sender, ImageClickEventArgs e)
{
// ExportToExcel();
if (ViewState["DashboardDetails"] != null)
{
lblError.Text = string.Empty;
lblError.Style.Add("display", "None");
grdHorizontalSeatDashboard.AllowPaging = false;
DataTable dtHorizontalDashboard = (DataTable)ViewState["DashboardDetails"];
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=HorizontalDashboard.xls");
Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdHorizontalSeatDashboard.AllowPaging = false;
grdHorizontalSeatDashboard.DataSource = (DataTable)ViewState["DashboardDetails"];
grdHorizontalSeatDashboard.DataBind();
grdHorizontalSeatDashboard.HeaderRow.BackColor = Color.White;
//Horizontal Cell
TableCell cell0 = grdHorizontalSeatDashboard.HeaderRow.Cells[0];
cell0.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell0.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[0].Width;
TableCell cell1 = grdHorizontalSeatDashboard.HeaderRow.Cells[1];
cell1.BackColor = ColorTranslator.FromHtml("#96B060");
cell1.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[1].Width;
TableCell cell2 = grdHorizontalSeatDashboard.HeaderRow.Cells[2];
cell2.BackColor = ColorTranslator.FromHtml("#96B060");
cell2.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[2].Width;
TableCell cell3 = grdHorizontalSeatDashboard.HeaderRow.Cells[3];
cell3.BackColor = ColorTranslator.FromHtml("#96B060");
cell3.Width = Unit.Pixel(100);
TableCell cell4 = grdHorizontalSeatDashboard.HeaderRow.Cells[4];
cell4.BackColor = ColorTranslator.FromHtml("#C57838");
cell4.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[4].Width;
TableCell cell5 = grdHorizontalSeatDashboard.HeaderRow.Cells[5];
cell5.BackColor = ColorTranslator.FromHtml("#C57838");
cell5.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[5].Width;
TableCell cell6 = grdHorizontalSeatDashboard.HeaderRow.Cells[6];
cell6.BackColor = ColorTranslator.FromHtml("#C57838");
cell6.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[6].Width;
// Likely $ Impact & Overall Horizontal Utilization
TableCell cell10 = grdHorizontalSeatDashboard.HeaderRow.Cells[10];
cell10.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell10.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[10].Width;
TableCell cell11 = grdHorizontalSeatDashboard.HeaderRow.Cells[11];
cell11.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell11.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[11].Width;
foreach (GridViewRow row in grdHorizontalSeatDashboard.Rows)
{
foreach (TableCell cell in row.Cells)
{
cell.BackColor = row.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.CssClass = "textmode";
}
}
foreach (TableCell cell in grdHorizontalSeatDashboard.FooterRow.Cells)
{
cell.BackColor = grdHorizontalSeatDashboard.FooterRow.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
}
Style style = new Style();
style.BackColor = Color.White;
Response.Write(style);
grdHorizontalSeatDashboard.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
To hide the first column or the first row (A1), just count the current row/column iteration and intercept the first and hide the A1 cell.
var rowCounter = 0;
var cellCounter = 0;
foreach (GridViewRow row in grdHorizontalSeatDashboard.Rows)
{
foreach (TableCell cell in row.Cells)
{
if (rowCounter == 0 && cellCounter == 0)
{
cell.Text = "";
}
cell.BackColor = row.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.CssClass = "textmode";
}
cellCounter = 0;
rowCounter++;
}
Related
i'm creating dynamic checkbox and textbox Control on page Load and i want to get the values of control on button click but we are not able to find out
here is my Dynamic control Code
DataTable dt = new DataTable();
da.Fill(dt);
var Count = dt.Rows.Count;
if (Count > 0)
{
TableHeaderRow thr = new TableHeaderRow();
TableHeaderCell cellheader = new TableHeaderCell();
TableHeaderCell thc = new TableHeaderCell();
TableHeaderCell thcode = new TableHeaderCell();
TableHeaderCell thcReason = new TableHeaderCell();
thc.Text = "Select";
thc.CssClass = "pd";
thcode.Text = "Description";
thcode.CssClass = "pdlbl";
thcReason.Text = "Reason";
thcReason.CssClass = "thcReason";
thr.Cells.Add(thc);
thr.Cells.Add(thcode);
thr.Cells.Add(thcReason);
tbl.Rows.Add(thr);
for (int i = 0; i < Count; i++)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
CheckBox chk = new CheckBox();
Label lbl = new Label();
TextBox txtBox = new TextBox();
txtBox.ID = "txt" + i.ToString();
txtBox.TextMode = TextBoxMode.MultiLine;
chk.ID = "chk" + i.ToString();
lbl.ID = "lbl" + i.ToString();
lbl.Text = dt.Rows[i]["DESCRIPTION"].ToString();
tc.Controls.Add(chk);
tc.Width = new Unit("5px");
tc.CssClass = "chkcntrl";
tc1.Controls.Add(lbl);
tc1.Width = new Unit("75%");
tc2.Controls.Add(txtBox);
tc2.Width = new Unit("20%");
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tbl.Rows.Add(tr);
}
tbl.EnableViewState = true;
ViewState["tbl"] = true;
}
after create the control i want to find out the values
my code are below
foreach (TableRow tr in tbl.Controls)
{
string str_Confirmed = string.Empty;
string str_Description = string.Empty;
string str_Reason = string.Empty;
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[0] is CheckBox)
{
if (((CheckBox)tc.Controls[0]).Checked == true)
{
str_Confirmed = "Y";
}
else
{
str_Confirmed = "N";
}
}
if (tc.Controls[1] is Label)
{
string txt = string.Empty;
str_Description = ((Label)tc.Controls[1]).Text;
}
if (tc.Controls[2] is TextBox)
{
str_Reason = ((TextBox)tc.Controls[2]).Text;
//Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
but when i will execute this code we are getting the Specified argument was out of the range of valid values. Parameter name: index please any one can tell me where am wrong
You have different table cells for each control you are adding.
tc has the checkbox control
tc1 has the label control
EDIT: A few other changes were needed to your code.
You were iterating through, tbl.Controls not tbl.Rows
You were iterating through tr.Controls not tr.Cells
The first table row you add is the header information that has no
controls so added check that controls.count() is greater than 0
Hope this helps
foreach (TableRow tr in tbl.Rows)
{
string str_Confirmed = string.Empty;
string str_Description = string.Empty;
string str_Reason = string.Empty;
foreach (TableCell tc in tr.Cells)
{
if (tc.Controls.Count > 0)
{
if (tc.Controls[0] is CheckBox)
{
if (((CheckBox)tc.Controls[0]).Checked == true)
{
str_Confirmed = "Y";
}
else
{
str_Confirmed = "N";
}
}
else if (tc.Controls[0] is Label)
{
string txt = string.Empty;
str_Description = ((Label)tc.Controls[1]).Text;
}
else if (tc.Controls[0] is TextBox)
{
str_Reason = ((TextBox)tc.Controls[2]).Text;
//Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
}
}
In a C# application I created a GridView dynamically and exported it to Excel. The issue that I am having is that since three fields are Bit columns in SQL they export as checkboxes and not ones and zeros. I have done some searching on google for similar issues and found this article this solution. However, this will not work out since right or left clicking on the object only checks or unchecks the box.
I have also tried to find information on how to export the bit fields as 1's and 0's from C# and have not been able to find anything. Here is my export script:
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
GridView gridView = new GridView();
gridView.DataSource = sdsResults;
gridView.AutoGenerateColumns = true;
gridView.DataBind();
gridView.HeaderRow.Style.Add("background-color", "#003c74");
gridView.HeaderRow.Style.Add("color", "#ffffff");
for (int i = 0; i < gridView.Rows.Count; i++)
{
GridViewRow row = gridView.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.BackColor = System.Drawing.Color.AliceBlue;
}
foreach(TableCell cell in row.Cells)
{
if(cell.HasControls() == true)
{
if(cell.Controls[0].GetType().ToString() == "System.Web.Ui.WebControls.CheckBox")
{
CheckBox chk = (CheckBox)cell.Controls[0];
if(chk.Checked)
{
cell.Text = "1";
}
else
{
cell.Text = "0";
}
}
}
}
}
gridView.RenderControl(htmlWriter);
htmlWriter.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=myfile.xls");
Response.Charset = "";
Response.Write(writer.ToString());
Response.End();
Response.End();
in the for loop, you can do something like this:
foreach(TableCell cell in row.Cells)
{
if(cell.HasControls() == true)
{
if(cell.Controls[0].GetType().ToString() == "System.Web.UI.WebControls.CheckBox")
{
CheckBox chk = (CheckBox)cell.Controls[0];
if(chk.Checked)
{
cell.Text = "1";
}
else{
cell.Text = "0";
}
}
}
}
If you're building the datasource with a SQL query then CAST the bit columns as int or varchar. If that can't be done try defining the GridView columns with desired data types before assigning the datasource.
protected void btnXlsExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvStandard.AllowPaging = false;
gvStandard.DataBind();
for (int i = 0; i <= gvStandard.Rows.Count - 1; i++) {
GridViewRow row = gvStandard.Rows(i);
foreach (TableCell cell in row.Cells) {
if (cell.HasControls() == true) {
if (cell.Controls(0).GetType().ToString() == "System.Web.UI.WebControls.CheckBox") {
CheckBox chk = (CheckBox)cell.Controls(0);
if (chk.Checked) {
cell.Text = "True";
} else {
cell.Text = "False";
}
}
}
}
}
gvStandard.HeaderRow.Style.Add("background-color", "#FFFFFF");
gvStandard.RenderControl(hw);
Response.Output.Write(sw);
Response.Flush();
Response.End();
}
Protected Sub btnXlsExport_Click(sender As Object, e As EventArgs) Handles btnXlsExport.Click
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
gvStandard.AllowPaging = False
gvStandard.DataBind()
For i As Integer = 0 To gvStandard.Rows.Count - 1
Dim row As GridViewRow = gvStandard.Rows(i)
For Each cell As TableCell In row.Cells
If cell.HasControls() = True Then
If cell.Controls(0).[GetType]().ToString() = "System.Web.UI.WebControls.CheckBox" Then
Dim chk As CheckBox = DirectCast(cell.Controls(0), CheckBox)
If chk.Checked Then
cell.Text = "True"
Else
cell.Text = "False"
End If
End If
End If
Next
Next
gvStandard.HeaderRow.Style.Add("background-color", "#FFFFFF")
gvStandard.RenderControl(hw)
Response.Output.Write(sw)
Response.Flush()
Response.End()
End Sub
Hi there i have this code to export my data gridview to excel
and my problem is that, the gridview shows a 12hr format but when i export it to excel it shows a 24hr format, how ca i make it into 12 hr format? thank you.
DataSet ds = (DataSet)ViewState["audit"];
DataTable dt = new DataTable();
dt = ds.Tables[0];
Table table = new Table();
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
for (int i = 0; i < AuditTrailGV.HeaderRow.Cells.Count; i++)
{
AuditTrailGV.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
AuditTrailGV.HeaderRow.Style.Add("border-color", "#FFFFFF");
int j = 1;
foreach (GridViewRow gvrow in AuditTrailGV.Rows)
{
//gvrow.BackColor = color.White;
gvrow.Style.Add("background-color", "#FFFFFF");
gvrow.Style.Add("border-color", "#bfc2c7");
if (j <= AuditTrailGV.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
else
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
}
j++;
}
foreach (GridViewRow row in AuditTrailGV.Rows)
{
table.Rows.Add(row);
}
TableHeaderCell header = new TableHeaderCell();
header.RowSpan = 1;
header.ColumnSpan = 6;
header.Text = "Inventory Accounting and Control System";
header.Font.Bold = true;
header.HorizontalAlign = HorizontalAlign.Center;
header.VerticalAlign = VerticalAlign.Middle;
header.Font.Size = 20;
TableRow headerrow = new TableRow();
headerrow.Cells.Add(header);
TableHeaderCell header2 = new TableHeaderCell();
header2.RowSpan = 1;
header2.ColumnSpan = 6;
header2.Text = "Audit Trail";
header2.Font.Bold = true;
header2.HorizontalAlign = HorizontalAlign.Center;
header2.VerticalAlign = VerticalAlign.Middle;
header2.Font.Size = 16;
TableRow headerrow2 = new TableRow();
headerrow2.Cells.Add(header2);
TableHeaderCell header3 = new TableHeaderCell();
header3.RowSpan = 1;
header3.ColumnSpan = 6;
header3.Text = DatefromTxtBox.Text + " to " + DatetoTxtBox.Text;
header3.Font.Bold = true;
header3.HorizontalAlign = HorizontalAlign.Center;
header3.VerticalAlign = VerticalAlign.Middle;
header3.Font.Size = 16;
TableRow headerrow3 = new TableRow();
headerrow3.Cells.Add(header3);
table.Rows.AddAt(0, headerrow);
table.Rows.AddAt(1, headerrow2);
table.Rows.AddAt(2, headerrow3);
table.Rows.AddAt(3, AuditTrailGV.HeaderRow);
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "IACSAuditTrail" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
table.RenderControl(htw);
Response.Write(sw.ToString());
Response.End()
This it what it looks
but this is what i looks when i export it to excel :(
The only way to save date format is to pre-format the date field as text and then export to excel. To do this,
string style = #"<style> TD { mso-number-format:\#; } </style> ";
Response.write(style);
//Code to Export Control
Panel1.RenderControl(htmlWrite);
you can refer to below link for more information
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
I am writing a code to make sure that if the translate button is pressed a new row appears but all the row members except string text are visible..Now i have written the code but it only makes the button disappear and all the members are still visible.
This is the view after the button is pressed..
Now the button is invisible but all the other members are still visible.this is the code i have tried..
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
bool ce = false;
bool check = true;
Column_handling();
DataGridViewTextBoxCell c = new DataGridViewTextBoxCell();
if(!(dataGridView1.Rows[e.RowIndex].Selected))
{
dataGridView1.Rows[e.RowIndex].Selected = false;
if (e.ColumnIndex == 10)
{
if((Convert.ToInt16(this.dataGridView1.Rows[e.RowIndex].Cells[0].Value) == Convert.ToInt16(this.dataGridView1.Rows[e.RowIndex + 1].Cells[0].Value)) && (Convert.ToInt16(this.dataGridView1.Rows[e.RowIndex].Cells[1].Value) == Convert.ToInt16(this.dataGridView1.Rows[e.RowIndex + 1].Cells[1].Value)))
{
ce = true;
}
if(!ce)
{
DataRow dt = datarows.NewRow();
dt[0] = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
dt[1] = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
dt[2] = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
dt[3] = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
dt[4] = this.dataGridView1.CurrentRow.Cells[4].Value.ToString();
dt[5] = this.dataGridView1.CurrentRow.Cells[5].Value.ToString();
dt[6] = this.dataGridView1.CurrentRow.Cells[6].Value.ToString();
dt[7] = this.dataGridView1.CurrentRow.Cells[7].Value.ToString();
dt[8] = this.dataGridView1.CurrentRow.Cells[8].Value.ToString();
dt[9] = this.dataGridView1.CurrentRow.Cells[9].Value.ToString();
datarows.Rows.InsertAt(dt, e.RowIndex + 1);
var row = this.dataGridView1.Rows[e.RowIndex + 1];
DataGridViewColumn column = dataGridView1.Columns[2];
DataGridViewCell cella = new DataGridViewTextBoxCell();
cella.Style.BackColor = Color.Wheat;
column.CellTemplate = cella;
var cell = new DataGridViewTextBoxCell();
cell.Value = string.Empty;
var cell1 = new DataGridViewTextBoxCell();
cell1.Value = string.Empty;
var cell2 = new DataGridViewTextBoxCell();
cell2.Value = string.Empty;
var cell3 = new DataGridViewTextBoxCell();
cell3.Value = string.Empty;
var cell4 = new DataGridViewTextBoxCell();
cell4.Value = string.Empty;
var cell5 = new DataGridViewTextBoxCell();
cell5.Value = string.Empty;
var cell6 = new DataGridViewTextBoxCell();
cell6.Value = string.Empty;
var cell7 = new DataGridViewTextBoxCell();
cell7.Value = string.Empty;
var cell8 = new DataGridViewTextBoxCell();
cell8.Value = string.Empty;
var cell9 = new DataGridViewTextBoxCell();
cell9.Value = string.Empty;
var cell10 = new DataGridViewTextBoxCell();
cell10.Value = string.Empty;
row.Cells[10] = cell;//the button column
row.Cells[0] = cell2;
row.Cells[1] = cell3;
row.Cells[3] = cell4;
row.Cells[4] = cell5;
row.Cells[5] = cell6;
row.Cells[6] = cell7;
row.Cells[7] = cell8;
row.Cells[8] = cell9;
row.Cells[9] = cell10;
cell.ReadOnly = true;
dataGridView1.ReadOnly = true;
dataGridView1.Refresh();
}
else if (!cao)
{
dataGridView1.Rows[e.RowIndex + 1].Visible = true;
var row = this.dataGridView1.Rows[e.RowIndex + 1];
var cell = new DataGridViewTextBoxCell();
cell.Value = string.Empty;
row.Cells[10] = cell;
cell.ReadOnly = true;
dataGridView1.Refresh();
cao = true;
}
else if (ce)
{
dataGridView1.Rows[e.RowIndex + 1].Visible = false;
var row = this.dataGridView1.Rows[e.RowIndex + 1];
var cell = new DataGridViewTextBoxCell();
cell.Value = string.Empty;
row.Cells[10] = cell;
cell.ReadOnly = true;
dataGridView1.Refresh();
cao= false;
}
}
}
}
I have following code that I am using for export to excel of a gridview. I am adding the gridview rows into System.Web.UI.WebControls.Table. Now, I need to apply background color to the header and data rows in the exported excel (There are two header rows).
I tired the following. It is not providing the desired result.
Issues of current solution
One header row does not have background color
Coloring is applied to cells that does not have data (cells “H”, “I”, etc.)
How can we correct it?
Note: I am trying to learn the export feature. So, please don't suggest to use any third party controls. I am just exploring all features of this approach.
I am adding the header grouping to the original gridview using following code.
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
System.Text.StringBuilder sbNewHeader = new StringBuilder();
sbNewHeader.AppendFormat(" </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();
}
}
Complete Code
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();
}
}
}
EDIT
Based on comment from Ankit, I tried the following; still the result is not as expected.
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);
}
If you want more control over how your excel files are written take a look at ClosedXML
Adding a table is as simple as
var wb = new XLWorkbook();
wb.Worksheets.Add(myDataTable);
wb.SaveAs("MySheet.xlsx");
Using the API you can code like this:
var rngTable = ws.Range("B2:F6");
rngTable.FirstCell().Style
.Font.SetBold()
.Fill.SetBackgroundColor(XLColor.CornflowerBlue)
.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
I figured a way to do it... For the benefit of others I will post it here:
References:
ASP.NET Excel export encoding problem
Other Note: When a new Table is created TableSection can be used to define header
newRow.TableSection = TableRowSection.TableHeader;
CODE
//Changed the logic used for adding dynamic header for HTML rendering:
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(" </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();
}
}
//Export Logic - Applied similar logic once again
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);
}
}
}