Subscribe to Subscribers

Forums » .NET » ASP.NET »

Export Gridview data to Excel


Posted Date: 10 Feb 2012      Posted By:: Rajeswari Bapatla     Member Level: Gold    Member Rank: 290     Points: 2   Responses: 6



As reference to my previous question

I have received the responses, but still the problem retains

after exporting the gridview to excel still the headers are not comming

after implementing the responses i have received.




Responses

#656669    Author: Asheej T K        Member Level: Diamond      Member Rank: 2     Date: 10/Feb/2012   Rating: 2 out of 52 out of 5     Points: 4

Hi,

Since you haven't provided the code you are using now it is hard to suggest where you are doing wrong.

Please Check below code,

This code can be used to export data from gridview to excel. So before using this code your datagrid should be populated with data from database.



private void ExportToExcel()
{
string Excelfilename = "Test_Excel_Export" + DateTime.Now;
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition:", "attachment; filename=" + Excelfilename + ".xls");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}


Let me know if this code doesn't export header in Excel.


Regards,
Asheej T K
Microsoft MVP[ASP.NET/IIS]
DotNetSpider MVM

Dotnet Galaxy


 
#656671    Author: Rajeswari Bapatla      Member Level: Gold      Member Rank: 290     Date: 10/Feb/2012   Rating: 2 out of 52 out of 5     Points: 1

Thanks Asheej,

i have worked out the same code, line by line but still
headers are not commings.

it is working fine when i am implementing in open office

but not in Microsoft office 2007


 
#656680    Author: Asheej T K        Member Level: Diamond      Member Rank: 2     Date: 10/Feb/2012   Rating: 2 out of 52 out of 5     Points: 2

Hi,

Do you have header template in GridView. can you post the .aspx page of gridview to know how you are using the Gridview?


Regards,
Asheej T K
Microsoft MVP[ASP.NET/IIS]
DotNetSpider MVM

Dotnet Galaxy





 
#656686    Author: Dharmaraj Nagarajan        Member Level: Gold      Member Rank: 16     Date: 10/Feb/2012   Rating: 1 out of 5     Points: 1


public void ExportGridToCSV(GridView gv, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", "myfile.csv"));
Response.Charset = "";

Response.ContentType = "application/vnd.csv";
System.IO.StringWriter myWriter;

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sWriter = new System.IO.StringWriter(sb);

string Str;

for (int k = 0; k <= (gv.Columns.Count - 1); k++)
{
sWriter.Write(gv.HeaderRow.Cells[k].Text + ",");
}

myWriter.WriteLine(",");

for (int i = 0; i <= (gv.Rows.Count - 1); i++)
{
for (int j = 0; j <= (gv.Columns.Count - 1); j++)
{
Str = (gv.Rows[i].Cells[j].Text.ToString().Replace("<BR />", ""));

if (Str == " ")
{
Str = "";
}


//Put quotation marks on either side of text

//so that commas in text are not treated as delimiters
Str = "\"" + Str + "\"" + ",";

myWriter.Write(Str);
}

myWriter.WriteLine();
}

myWriter.Close();

Response.Write(sb.ToString());
Response.End();
}



All is well.
Thanks,
Dharma
Editor,Mentor,MVM
Try and fail but don't fail and try
Me and DNS


 
#656725    Author: NareshGodera      Member Level: Silver      Member Rank: 1150     Date: 10/Feb/2012   Rating: 2 out of 52 out of 5     Points: 4

Hi,


Use the below Code it's working here.


protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
string fileName = "ScanningAndNonScan.xls";
string Extension = ".xls";
if (Extension == ".xls")
{
PrepareControlForExport(GridView1);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
HttpContext.Current.Response.ContentType = "application/ms-excel";
try
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();
table.GridLines = GridView1.GridLines;
// add the header row to the table
if (GridView1.HeaderRow != null)
{
PrepareControlForExport(GridView1.HeaderRow);
table.Rows.Add(GridView1.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in GridView1.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (GridView1.FooterRow != null)
{
PrepareControlForExport(GridView1.FooterRow);
table.Rows.Add(GridView1.FooterRow);
}
// render the table into the htmlwriter
GridView1.GridLines = GridLines.Both;
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
catch (HttpException ex)
{
throw ex;
}
}
}
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"));
}
else if (current is HiddenField)
{
control.Controls.Remove(current);
//control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}


 
#656752    Author: Naveen Reddy      Member Level: Gold      Member Rank: 15     Date: 11/Feb/2012   Rating: 1 out of 5     Points: 1

Hello,

Please have a look at the below code and update your code snippet.


public void ExportGridToMyCSV(GridView gvMygrid, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", "myfile.csv"));
Response.Charset = "";

Response.ContentType = "application/vnd.csv";

System.IO.StringWriter sWriter;

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sWriter = new System.IO.StringWriter(sb);

string MyString;

for (int k = 0; k <= (gvMygrid.Columns.Count - 1); k++)
{
sWriter.Write(gvMygrid.HeaderRow.Cells[k].Text + ",");
}

sWriter.WriteLine(",");

for (int i = 0; i <= (gvMygrid.Rows.Count - 1); i++)
{
for (int j = 0; j <= (gvMygrid.Columns.Count - 1); j++)
{
MyString = (gvMygrid.Rows[i].Cells[j].Text.ToString().Replace("<BR />", ""));

if (MyString == " ")
{
MyString = "";
}


//Put quotation marks on either side of text

//so that commas in text are not treated as delimiters
MyString = "\"" + MyString + "\"" + ",";

sWriter.Write(MyString);
}

sWriter.WriteLine();
}

sWriter.Close();

Response.Write(sb.ToString());
Response.End();
}


Regards,
Naveen


 
Post Reply

 This thread is locked for new responses. Please post your comments and questions as a separate thread.
If required, refer to the URL of this page in your new post.



Next : Re: Web service in asp.net
Previous : DataView Custom Sort
Return to Discussion Forum
Post New Message
Category:

Related Messages

Awards & Gifts
Talk to Webmaster Tony John
Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
2005 - 2013 All Rights Reserved.
.NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
Articles, tutorials and all other content offered here is for educational purpose only.
We are not associated with Microsoft or its partners.