export GridView to excel #2 - c#

I am binding a GridView to a sqldatasource and then on _rowcreated event doing some validations and when the row does not meet requirements I am hiding it using e.Row.Visible = false;
This works fine and only displays the correct rows in the gridview. Now I have a button to export to excel and that works great with the exception of exporting also the hidden rows. I do not want the hidden rows exported.
Is there a way that i can tell the gridview to not add that row instead of hiding it?
Is there a simple method to delete all hidden rows before i run the export?
Can i not add the hidden rows during the export? As you can see in the code below I tried to do this one, but it does not recognize whether the row is visible or not.
Export Code:
public static void Export(string fileName, GridView gv)
{
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();
gv.GridLines = GridLines.Both;
table.GridLines = gv.GridLines;
//table.BackColor = Color.Yellow;
// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
//color the header
table.Rows[0].BackColor = gv.HeaderStyle.BackColor;
table.Rows[0].ForeColor = gv.HeaderStyle.ForeColor;
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
if (row.Visible == true)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
}
// color the rows
bool altColor = false;
for (int i = 1; i < table.Rows.Count; i++)
{
if (!altColor)
{
table.Rows[i].BackColor = gv.RowStyle.BackColor;
altColor = true;
}
else
{
table.Rows[i].BackColor = gv.AlternatingRowStyle.BackColor;
altColor = false;
}
}
// 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();
}
}
}

http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
I have never used GridViewExportUtil, but why not edit his code?
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
//-----------------------------
// * my addition
if (!current.Visible) continue;
//-----------------------------
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
//...

Here is the simple implementation to Export GridView to Excel:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class ExportGridView : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
}
Reference blog

In the first place why you have hidden rows from your gridview? Only get data that you wanted. And use this method to export;
void ExportToExcel(GridView grdData, string filename)
{
grdData.BorderStyle = BorderStyle.Solid;
grdData.BorderWidth = 1;
grdData.BackColor = Color.WhiteSmoke;
grdData.GridLines = GridLines.Both;
grdData.Font.Name = "Verdana";
grdData.Font.Size = FontUnit.XXSmall;
grdData.HeaderStyle.BackColor = Color.DimGray;
grdData.HeaderStyle.ForeColor = Color.White;
grdData.RowStyle.HorizontalAlign = HorizontalAlign.Left;
grdData.RowStyle.VerticalAlign = VerticalAlign.Top;
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\"");
using (var sw = new StringWriter())
{
using (var htw = new HtmlTextWriter(sw))
{
grdData.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}

Related

Grid view is not being refreshed on exporting grid view to excel in asp.net

i am come up with scenario that while exporting grid view to excel its not refreshing my grid data source. Below is my code what i have done before. Below code is updating flag in database and then trying to refresh the grid data source in Fill Grid method.
protected void Process_Command(object sender, CommandEventArgs e)
{
if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
using (var transaction = context.Database.BeginTransaction())
{
DocumentOGP objDocumentOGP = context.DocumentOGPs.Find(Convert.ToInt64(e.CommandArgument));
objDocumentOGP.UpdationDate = DateTime.Now;
objDocumentOGP.DispatchStatusID = 2;
context.DocumentOGPs.Add(objDocumentOGP);
context.Entry(objDocumentOGP).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
transaction.Commit();
FillGrid();
}
ExportToExcel(Convert.ToInt64(e.CommandArgument));
}
}
Below is the Export to excel method.
public void ExportToExcel(Int64 OGPCode)
{
DataTable dtPickList =GeneralQuery.GetDocumentPickList(OGPCode);
if (dtPickList != null && dtPickList.Rows.Count>0)
{
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dtPickList;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Inbox.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
GridView1.DataSource = null;
Response.Write(Request.RawUrl.ToString());
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Please help me what i am doing wrong. Thanks
Finally i found the way to refresh the grid view while exporting the grid view to excel. I just create new web form and put ExportGridToExcel() method in Page_Load and on button click it refresh the grid view data source and open new tab to download excel file. Below is my code.
protected void Process_Command(object sender, CommandEventArgs e)
{
if (Session["Status"] != "Refreshed")
{
if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
using (var transaction = context.Database.BeginTransaction())
{
DocumentOGP objDocumentOGP = context.DocumentOGPs.Find(Convert.ToInt64(e.CommandArgument));
objDocumentOGP.UpdationDate = DateTime.Now;
objDocumentOGP.DispatchStatusID = 2;
context.DocumentOGPs.Add(objDocumentOGP);
context.Entry(objDocumentOGP).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
transaction.Commit();
FillGrid();
Session["OGPCode"] = Convert.ToString(e.CommandArgument);
}
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "OpenWindow", "window.open('http://localhost:56430/DownLoadExcel','_newtab');", true);
}
}
}
Below is my Download excel file web-form and its implementation
public partial class DownLoadExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Convert.ToString(Session["OGPCode"])))
{
ExportToExcel(Convert.ToInt64(Session["OGPCode"]));
Session["OGPCode"] = null;
}
}
}
public void ExportToExcel(Int64 OGPCode)
{
DataTable dt = GeneralQuery.GetDocumentPickList(OGPCode);
//create a new byte array
byte[] bin;
string FileName = "Pick-List-" + DateTime.Now.ToString();
//create a new excel document
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a new worksheet
ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add(FileName);
//add the contents of the datatable to the excel file
ws.Cells["A1"].LoadFromDataTable(dt, true);
//auto fix the columns
ws.Cells[ws.Dimension.Address].AutoFitColumns();
//loop all the columns
for (int col = 1; col <= ws.Dimension.End.Column; col++)
{
//make all columns just a bit wider, it would sometimes not fit
ws.Column(col).Width = ws.Column(col).Width + 1;
var cell = ws.Cells[1, col];
//make the text bold
cell.Style.Font.Bold = true;
//make the background of the cell gray
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));
//make the header text upper case
cell.Value = ((string)cell.Value).ToUpper();
}
//convert the excel package to a byte array
bin = excelPackage.GetAsByteArray();
}
//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
//set the correct contenttype
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//set the correct length of the data being send
Response.AddHeader("content-length", bin.Length.ToString());
//set the filename for the excel package
Response.AddHeader("content-disposition", "attachment; filename=\"" + FileName + ".xlsx\"");
//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);
//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
When you update GridView or any control values dynamically you should render and export it to other application.
Sample: check with RenderControl method of GridView.
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "xyz.xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
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

Asp.Net - Export two Gridviews to excel or pdf

I have a page that shows two grids side by side; "Expenses" and "Income".
I want the user to be able to export it to excel or pdf or print it as it's shown on the web page, side by side.
How can I do it?
What's the best practice?
Thanks.
Probably Reporting Services (SSRS)
but in case sql server
protected void btnExportExcel_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);
GridView1.AllowPaging = false;
// Re-Bind data to GridView
using (CompMSEntities1 CompObj = new CompMSEntities1())
{
Start = Convert.ToDateTime(txtStart.Text);
End = Convert.ToDateTime(txtEnd.Text);
GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
GridView1.DataBind();
GridView1.Visible = true;
ExportTable.Visible = true;
}
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.Style.Add(" font-size", "10px");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 1; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.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.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
For printing you can specify special styles using #media print { } block in CSS and initiate printing in browser manually or by calling window.print() in JavaScript.
For export to Excel you can use, for example, http://closedxml.codeplex.com/.
For export to PDF you can use, for example, http://sourceforge.net/projects/itextsharp/.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedIndex == 0)
{
GridView1.ShowHeader = true;
GridView1.GridLines = GridLines.Both;
GridView1.AllowPaging = false;
GridView1.DataBind();
}
else
{
GridView1.ShowHeader = true;
GridView1.GridLines = GridLines.Both;
GridView1.PagerSettings.Visible = false;
GridView1.DataBind();
}
ChangeControlsToValue(GridView1);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");
Response.ContentType = "application/excel";
StringWriter sWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
HtmlForm hForm = new HtmlForm();
GridView1.Parent.Controls.Add(hForm);
hForm.Attributes["runat"] = "server";
hForm.Controls.Add(GridView1);
hForm.RenderControl(hTextWriter);
// Write below code to add cell border to empty cells in Excel file
// If we don't add this line then empty cells will be shown as blank white space
StringBuilder sBuilder = new StringBuilder();
sBuilder.Append("<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"> <head><meta http-equiv="Content-Type" content="text/html;charset=windows-1252"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>ExportToExcel</x:Name><x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head> <body>");
sBuilder.Append(sWriter + "</body></html>");
Response.Write(sBuilder.ToString());
Response.End();
}

data transfer gird view to excel sheet

data transfer grid view to excel in asp dot net code is run but blank sheet generate of excel but data is not loaded in excel sheeet how to solve this type of broblem
protected void btnexcel_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=ActualsAndBudgets.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Check for data in the gridview, your data is not getting binded. So the excel is empty. Debug and check for data inside the gridview. It should work.
Try with this one
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=ActualsAndBudgets.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
may be problem in data binding in export excel .
check that data properly bin to a gridview or not.
Use this code for export grid view in excel sheet and note that you must add iTextSharp dll in you project.
protected void btnExportExcel_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);
GridView1.AllowPaging = false;
// Re-Bind data to GridView
using (CompMSEntities1 CompObj = new CompMSEntities1())
{
Start = Convert.ToDateTime(txtStart.Text);
End = Convert.ToDateTime(txtEnd.Text);
GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
GridView1.DataBind();
GridView1.Visible = true;
ExportTable.Visible = true;
}
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.Style.Add(" font-size", "10px");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 1; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.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.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

Download Selected Row of Gridview to excel

I need to download selected rows of an asp.net gridview to an excel sheet.
What I am doing is trying the check all at once or just a few selected and then after pressing the download button below, all the selected rows get downloaded as excel. Every thing works fine here when I press download button, but rather all the rows get downloaded ignoring the selection.
Following is my code
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// I Tried using following (but with no success)
//-----Trial Starts----------------
//foreach (GridViewRow gvr in gvProgramList.Rows)
// {
// CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
// if(cbox.Checked)
// gvr.Visible = true;
// else
// gvr.Visible = false;
// }
//--------Trial ends---------------
grdGridView.DataBind();
ClearControls(grdGridView);
// Throws exception: Control 'ComputerGrid' of type 'GridView'
// must be placed inside a form tag with runat=server.
// ComputerGrid.RenderControl(htmlWrite);
// Alternate to ComputerGrid.RenderControl above
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(grdGridView);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
foreach (GridViewRow gvr in gvProgramList.Rows)
{
CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
gvr.Visible = true;
}
grdGridView.DataBind();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
protected void btnDownload_Click(object sender, EventArgs e)
{
if (gvProgramList.Rows.Count > 0)
{
ExportGridToExcel(gvProgramList, "ProgramList");
}
}
I can suggest you a logic to do this:
1.Create a dynamic datatable with selected rows of your gridview.
its just looping through gridview rows and fetching and appending selected rows to new datatable.
2.Then write code for converting this new datatable to excel sheets(lots of results for google "Convert datatable to excel")
Try like the below code,hope it helps you..
On the download button click event,call this fn
private void ExportToExcell()
{
DataTable dt = new DataTable();
dt.Columns.Add("Plan ID");
dt.Columns.Add("Plan Name");
dt.Columns.Add("Balance");
foreach (GridViewRow row in gdvBal.Rows)
{
CheckBox chkCalls = (CheckBox)row.FindControl("chkCalls");
if (chkCalls.Checked == true)
{
int i = row.RowIndex;
Label lblPlanId = (Label)gdvBal.Rows[i].FindControl("lblPlanId");
Label lblPlanName = (Label)gdvBal.Rows[i].FindControl("lblPlanName");
Label lblBalance = (Label)gdvBal.Rows[i].FindControl("lblBalance");
DataRow dr = dt.NewRow();
dr["Plan ID"] = Convert.ToString(lblPlanId.Text);
dr["Plan Name"] = Convert.ToString(lblPlanName.Text);
dr["Balance"] = Convert.ToString(lblBalance.Text);
dt.Rows.Add(dr);
}
}
GridView gdvExportxls = new GridView();
gdvExportxls.DataSource = dt;
gdvExportxls.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename=BillingForfBalances.xls", "selectedrows"));
Response.Charset = "";
StringWriter stringwriter = new StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
gdvExportxls.RenderControl(htmlwriter);
Response.Write(stringwriter.ToString().Replace("<div>", " ").Replace("</div>", " "));
Response.End();
}

Categories

Resources