Click here to Skip to main content
Sign Up to vote bad
good
See more: C#ASP.NETHTML
HI,
I need to export Gridview contents to an excel sheet. I tried searching and got many solutions. Among them i used the most simple one. But the problem is that it is exporting the entire HTML page instead of selected GridView. Here's my code:
protected void exportToExcel_Click(object sender, EventArgs e)
    {
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
        try
        {
            
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
            Response.Charset = "";
            GridView1.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
            
        }
        catch (Exception except1)
        {
            Response.Write(except1);
        }
    }
 
Please suggest me how to do the exporting stuff. I'm new to C# environment.
Posted 6 Jan '13 - 22:06
Edited 6 Jan '13 - 22:24

Comments
Christian Graus - 7 Jan '13 - 4:12
This is way too complex for people new to C#. Why are you doing it ?
Sriram Mani - 7 Jan '13 - 4:34
Graus, Just to learn.
Christian Graus - 7 Jan '13 - 4:36
Well, if you're new to C#, it's a dumb learning project. Learn to program, not to interact with Excel. Even ASP.NET is a bad choice to learn C#, winforms is far better.
Sriram Mani - 7 Jan '13 - 4:36
Graus, I'm developing an ASP.NET website. I just wanted to have the functionality of exporting data from a gridview to excel.
Christian Graus - 7 Jan '13 - 4:37
So you're not 'just learning' at all. Didn't think so.
Sriram Mani - 7 Jan '13 - 4:43
Graus, I'm learning to develop an ASP.NET site.. and completed some level in it. Trying to move to the new level(of learning ofcourse).
Christian Graus - 7 Jan '13 - 4:51
I recommend learning jquery and AJAX through jquery, that's generally useful stuff, what you're doing now, you'll hardly ever use.
Sriram Mani - 7 Jan '13 - 4:54
Thanks Graus, I'll start learning them. If you have had any ideas about this exporting stuff, please guide me. Thanks in advance.

4 solutions

Hi,
 
If your filling your grid view by fetching data from database then following will be useful to you...
 
protected void btnExport_Click(object sender, EventArgs e)
{

try
{
string strconstring = ConfigurationManager.AppSettings["con"]; //database connection string from web.config file
SqlConnection cn = new SqlConnection(strconstring); // connection to DB
 
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
string strSQL = "";
cn.Open();

strSQL = "select * from table1 "; //your select query which display data in gridview
<pre lang="text">
}
da.SelectCommand = new SqlCommand(strSQL, cn);
da.Fill(dt);
 
//DataTable dt = new DataTable();
 
//dt = (DataTable)Session["MonthlyCostingData"];
 
Response.Clear();
 

string attachment = "attachment; filename=AfterSalesPerformance_" + DateTime.Now.Date.ToString() + ".xls";
 
Response.ClearContent();
 
Response.AddHeader("content-disposition", attachment);
 
Response.ContentType = "application/vnd.ms-excel";
 
string tab = "";
 

foreach (DataColumn dc in dt.Columns)
{
 
Response.Write(tab + dc.ColumnName);
 
tab = "\t";
 
}
 
Response.Write("\n");
 

int i;
 
foreach (DataRow dr in dt.Rows)
{
 
tab = "";
 
for (i = 0; i < dt.Columns.Count; i++)
{
//dr[i].Style.Add("background-color", "#FFFFC0");
 
Response.Write(tab + dr[i].ToString());
 
tab = "\t";
 
}
 
Response.Write("\n");
 
}
 
Response.End();
}
#endregion
 
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
  Permalink  
Comments
Sriram Mani - 7 Jan '13 - 4:31
Thanks ranjitwaje, I'm using Access Datasource to fill the Grid view. Is there any possibilities to do exporting with that..?? Not by using Datatable or Dataadapter etc.,
If you want to export data from Directly gridview then you can try this code.
It will export the GridView Data in Excel regardless of source of database.
 

string filename = "EmployeeRecord.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

 
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());

 
Response.End();
 
Hopefully It will help you.
  Permalink  
Comments
Sriram Mani - 7 Jan '13 - 6:03
Thanks Syed Ali Raza, I'm afraid that you might have posted back the question which i asked.
Sorry I don't have any idea about any kind of such possibilities..
  Permalink  
Comments
Sriram Mani - 7 Jan '13 - 4:49
Thanks ranjitwaje. I'll post the solution if i find one.
try this.
recently encountered a similar problem as yours
 
Response.Clear()
          Response.ClearHeaders()
          Response.AddHeader("content-disposition", "attachment; filename=" + newTempFile)
          Response.AddHeader("content-length", New FileInfo(filePath + newTempFile).Length.ToString())
          Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
 
          Response.WriteFile(Server.MapPath("~/temp/") + newTempFile)
          Response.Flush()
          File.Delete(Server.MapPath("~/temp/") + newTempFile)
          Response.End()
 
please change the variable like filePath, newTempFile etc to suite your needs
 
and make sure you have given proper permissions on your webserver.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 445
1 OriginalGriff 295
2 Arun Vasu 253
3 Zoltán Zörgő 194
4 CPallini 173
0 Sergey Alexandrovich Kryukov 10,105
1 OriginalGriff 7,739
2 CPallini 4,181
3 Rohan Leuva 3,482
4 Maciej Los 2,999


Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 7 Jan 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid