Click here to Skip to main content
11,480,938 members (63,689 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ASP.NET HTML
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 23:06pm
Edited 6-Jan-13 23:24pm
v2
Comments
Christian Graus at 7-Jan-13 4:12am
   
This is way too complex for people new to C#. Why are you doing it ?
Sriram Mani at 7-Jan-13 4:34am
   
Graus,
Just to learn.
Christian Graus at 7-Jan-13 4:36am
   
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 at 7-Jan-13 4:36am
   
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 at 7-Jan-13 4:37am
   
So you're not 'just learning' at all. Didn't think so.
Sriram Mani at 7-Jan-13 4:43am
   
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 at 7-Jan-13 4:51am
   
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 at 7-Jan-13 4:54am
   
Thanks Graus,
I'll start learning them. If you have had any ideas about this exporting stuff, please guide me.

Thanks in advance.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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 at 7-Jan-13 4:31am
   
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.,
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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  
v2
Comments
Sriram Mani at 7-Jan-13 6:03am
   
Thanks Syed Ali Raza,
I'm afraid that you might have posted back the question which i asked.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Sorry I don't have any idea about any kind of such possibilities..
  Permalink  
Comments
Sriram Mani at 7-Jan-13 4:49am
   
Thanks ranjitwaje. I'll post the solution if i find one.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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
0 Sergey Alexandrovich Kryukov 294
1 CPallini 135
2 OriginalGriff 130
3 CHill60 130
4 Member 10254688 65
0 Sergey Alexandrovich Kryukov 8,184
1 OriginalGriff 7,586
2 Sascha Lefèvre 3,114
3 Maciej Los 2,491
4 Richard Deeming 2,335


Advertise | Privacy | Mobile
Web03 | 2.8.150520.1 | Last Updated 7 Jan 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100