How to print a text before writing grid data to Excel - c#

I am trying to print a text " This is my customer information" into an Excel file before writing GridView data to Excel. This text should be in top and remaining data should display below this text.
Can anyone help me? How can I do it? Please check my current code. This code just writes my GridView data to an Excel file.
protected void ExportToExcel(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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
Search(null, null);
// GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
// row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
//table.Rows.Add(title);
}
GridView1.Columns[7].Visible = false;
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}

Boils down to
Response.Write("Some cool text added before the grid");
before
Response.Output.Write(sw.ToString());
.
using System;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Collections.ObjectModel;
namespace AddTextToDataGridExportExcel_46000670
{
public partial class Default : System.Web.UI.Page
{
static ObservableCollection<gridEntry> gridDataSource = new ObservableCollection<gridEntry>();
protected void Page_Load(object sender, EventArgs e)
{
fillDataSource();
initializeGridView();
}
private void fillDataSource()
{
gridDataSource.Add(new gridEntry(1));
gridDataSource.Add(new gridEntry(2));
gridDataSource.Add(new gridEntry(3));
gridDataSource.Add(new gridEntry(4));
gridDataSource.Add(new gridEntry(5));
}
private void initializeGridView()
{
GridView1.DataSource = gridDataSource;
GridView1.DataBind();
}
protected void ExportToExcel(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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
addRowToGrid();//add text within the grid
initializeGridView();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Write("blah blah blah");//add text before the grid
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
private void addRowToGrid()
{
gridDataSource.Insert(0, new gridEntry { col1 = "this is my added text" });
}
private GridView addRowToGridAgain(GridView gv)
{
return gv;
}
protected void btn_ClickMe_Click(object sender, EventArgs e)
{
ExportToExcel(null, null);
}
}
public class gridEntry
{
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
public string col4 { get; set; }
public string col5 { get; set; }
public string col6 { get; set; }
public string col7 { get; set; }
public string col8 { get; set; }
public gridEntry()
{
col1 = string.Empty;
col2 = string.Empty;
col3 = string.Empty;
col4 = string.Empty;
col5 = string.Empty;
col6 = string.Empty;
col7 = string.Empty;
col8 = string.Empty;
}
public gridEntry(int index)
{
col1 = "col1 " + index.ToString();
col2 = "col2 " + index.ToString();
col3 = "col3 " + index.ToString();
col4 = "col4 " + index.ToString();
col5 = "col5 " + index.ToString();
col6 = "col6 " + index.ToString();
col7 = "col7 " + index.ToString();
col8 = "col8 " + index.ToString();
}
}
}
Below is YOUR snippet, fixed
//GridView1.Columns[7].Visible = false; was throwing an error, so I commented it out. That's up to you to figure out, or ask a new question for it
Don't know what Search(null, null); does, so I commented it out
protected void ExportToExcelPosterWay(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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
//Search(null, null);
initializeGridView();
// GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
// row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
//table.Rows.Add(title);
}
//GridView1.Columns[7].Visible = false;
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Write("Some cool text added before the grid");
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}

Related

button to export tables to excel in asp.net

I have few pages of tables, and I have created a button to export the table to excel. my problem is that it only export the current page of table that in at and not all the pages? can anyone help me out?
protected void ExportToExcel(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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}

Export data from Gridview to Excel in asp.net

I am Having Error while Exporting data from Gridview to Excel in asp.net
Firebug shows that error is
"Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '
and my code is
EditUser _editUser = new EditUser();
string s = Request.QueryString["UserName"];
DataTable _dsLeaveDetails1 = new DataTable();
_dsLeaveDetails1 = _editUser.GetUserWiseECO(s.ToLower(), "Earned Comp Off");
if (_dsLeaveDetails1.Rows.Count > 0)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MonthlyLeaveReport.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
sample.AllowPaging = false;
sample.DataSource = _dsLeaveDetails1;
sample.DataBind();
//Change the Header Row back to white color
sample.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < sample.HeaderRow.Cells.Count; i++)
{
sample.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in sample.Rows)
{
gvrow.BackColor = Color.White;
if (j <= sample.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
sample.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "alert('No records Found!!!');", true);
}
This is the complete code I'm using.
First override this method:
public override void VerifyRenderingInServerForm(Control control)
{
}
And use this method to export to Excel:
private void ExportToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=name.xls");
Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
gridview.AllowPaging = false;
gridview.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in gridview.HeaderRow.Cells)
{
cell.BackColor = Color.FromName("#4091A4");
cell.ForeColor = Color.White;
foreach (Control control in cell.Controls)
{
if ((control.GetType().Name == "DataControlLinkButton") ||
(control.GetType().Name == "DataControlLinkButton"))
{
cell.Controls.Add(new Literal { Text = (control as LinkButton).Text });
cell.Controls.Remove(control);
}
}
}
foreach (GridViewRow row in gridview.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
List<Control> controls = new List<Control>();
foreach (Control control in cell.Controls)
{
controls.Add(control);
}
cell.CssClass = "textmode";
foreach (Control control in controls)
{
switch (control.GetType().Name)
{
case "HyperLink":
cell.Controls.Add(new Literal { Text = (control as HyperLink).Text });
break;
case "TextBox":
cell.Controls.Add(new Literal { Text = (control as TextBox).Text });
break;
case "DataControlLinkButton":
case "LinkButton":
cell.Controls.Add(new Literal { Text = (control as LinkButton).Text });
break;
case "CheckBox":
cell.Controls.Add(new Literal { Text = (control as CheckBox).Text });
break;
case "RadioButton":
cell.Controls.Add(new Literal { Text = (control as RadioButton).Text });
break;
}
cell.Controls.Remove(control);
}
if (row.RowIndex % 2 == 0)
{
cell.BackColor = gridview.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = gridview.RowStyle.BackColor;
}
cell.HorizontalAlign = HorizontalAlign.Center;
}
}
gridview.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}

How to manually add Excel columns headers for a generated spreadsheet

I have developed an excel sheet using c# gridview. How do I add a header row and set column names via code. This is my current code...
protected void ExportToExcel1(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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
bindgrid();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}

Export multiple gridviews to multiple excel tabs (sheets)

I have 6 gridviews in my website that I need to export to excel, but each one in one different sheet.
This link Export GridView to multiple Excel sheet uses something quite similar, but he is using datasets and I am not. I am new to C#, so I couldnt change it to fit my solution.
My code exports all gridviews to the same sheet. I created a loop to run throught my gridviews, now I need to put a code to generate each one to each excel sheet.
protected void btExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FARPOP_Mensal_" + txDt.Text + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("Windows-1252");
Response.Charset = "ISO-8859-1";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView[] gvExcel = new GridView[] { gvAnual, gvPorUF, gvPorFarmacia, gvPorMunicipio, gvPorPV, gvPorCNPJ };
for (int i = 0; i < gvExcel.Length; i++)
{
GridView gv = gvExcel[i];
//
// Need to redirect to each sheet here?
//
gvExcel[i].HeaderRow.BackColor = Color.White;
gvExcel[i].UseAccessibleHeader = false;
gvExcel[i].AllowPaging = false;
for (int x = 0; x < gvExcel[i].Columns.Count; x++)
{
gvExcel[i].Columns[x].Visible = true;
}
gvExcel[i].DataBind();
foreach (TableCell cell in gvExcel[i].HeaderRow.Cells)
{
cell.BackColor = Color.CadetBlue;
cell.Enabled = false;
}
foreach (GridViewRow row in gvExcel[i].Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.Controls.Clear();
if (row.RowIndex % 2 == 0)
{
cell.BackColor = Color.White;
}
else
{
cell.BackColor = Color.LightBlue;
}
cell.CssClass = "textmode";
}
}
gvExcel[i].RenderControl(hw);
}
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
I followed maniak1982 comments and found a good solution.
So, if you need multiple gridviews to multiples worksheets, using .NET, you will need to download ClosedXML and also DocumentFormat.OpenXml.dll.
After referencing the dll, use the following code:
protected void btExcel_Click(object sender, EventArgs e)
{
XLWorkbook wb = new XLWorkbook();
GridView[] gvExcel = new GridView[] { GridView1, GridView2, GridView3, GridView4, GridView5, GridView6};
string[] name = new string[] { "Name1", "Name2", "Name3", "Name4", "Name5", "Name6" };
for (int i = 0; i < gvExcel.Length; i++)
{
if (gvExcel[i].Visible)
{
gvExcel[i].AllowPaging = false;
gvExcel[i].DataBind();
DataTable dt = new DataTable(name[i].ToString());
for (int z = 0; z < gvExcel[i].Columns.Count; z++)
{
dt.Columns.Add(gvExcel[i].Columns[z].HeaderText);
}
foreach (GridViewRow row in gvExcel[i].Rows)
{
dt.Rows.Add();
for (int c = 0; c < row.Cells.Count; c++)
{
dt.Rows[dt.Rows.Count - 1][c] = row.Cells[c].Text;
}
}
wb.Worksheets.Add(dt);
gvExcel[i].AllowPaging = true;
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Workbook_Name.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
It took me days of searching... But it's working perfectly.
Be happy

Export gridview in excel

I have two gridviews on a page. When I click on Button3 it exports gridview data to excel perfectly.
but when I click on Button5 it exports data of gridview to excel and in excel file contains only:
<style> .textmode { } </style><div>
here is my c# code:
protected void Button3_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ExportFile.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.Columns[0].Visible = false;
GridView1.Columns[1].Visible = false;
//GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
this.GridView1.DataBind();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
protected void Button5_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ExportFile.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView2.AllowPaging = false;
GridView2.Columns[0].Visible = false;
GridView2.Columns[1].Visible = false;
//GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
this.GridView2.DataBind();
GridView2.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView2.HeaderRow.Cells)
{
cell.BackColor = GridView2.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView2.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView2.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView2.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView2.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}

Categories

Resources