Export SPGridView to Excel spreadsheet in Sharepoint 2007
In my last post I have show you how to retrieve current user profile in Sharepoint 2007, before that I have also posted on how to display custom list items in SPGridView
Today I am going to work on how to export SPGridView items into Excel spreadsheet in Sharepoint 2007
Most of the code I have used form Matt Berseth blog article Export GridView to Excel so thanks to Matt and also thanks to my colleague Ram Gowri who helped me on this
To run the code first you need to create a custom list, name it as Countries, then create two columns int he same list Country and State
using System;
using System.IO;
using System.Web;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace ExportGridtoExcel
{
[Guid("2fa65763-1ef1-4173-8a77-685e840f0196")]
public class ExportGridtoExcel : System.Web.UI.WebControls.WebParts.WebPart
{
SPGridView myGridView;
SPDataSource myDataSource = new SPDataSource();
Button oBtn_Export;
protected override void CreateChildControls()
{
oBtn_Export = new Button();
oBtn_Export.Text = "Export to Excel";
oBtn_Export.CssClass = "ButtonHeightWidth";
oBtn_Export.Click += new EventHandler(oBtn_Export_Click);
this.Controls.Add(oBtn_Export);
myGridView = new SPGridView();
myGridView.Enabled = true;
myGridView.AutoGenerateColumns = false;
SPBoundField colTitle = new SPBoundField();
colTitle.DataField = "Country";
colTitle.HeaderText = "Country";
this.myGridView.Columns.Add(colTitle);
SPBoundField colMission = new SPBoundField();
colMission.DataField = "State";
colMission.HeaderText = "State";
this.myGridView.Columns.Add(colMission);
this.Controls.Add(myGridView);
}
void oBtn_Export_Click(object sender, EventArgs e)
{
ExportToExcel("CountryState.xls", myGridView);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = SPContext.Current.Web;
SPList list = myWeb.Lists["Countries"];
myDataSource.List = list;
myGridView.DataSource = myDataSource;
myGridView.DataBind();
}
public static void ExportToExcel(string strFileName, SPGridView gv)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", strFileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
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"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
}
}
Comments
Comment from G Vijai Kumar
Time August 24, 2009 at 2:13 pm
@ Cango, please follow the Mattberseth post so that you will be able to export all pages data too http://mattberseth2.com/demo/Default.aspx?Name=Export+GridView+to+Excel&Filter=All
Comment from Kien Tran
Time March 23, 2010 at 6:43 pm
Great post. I’d like to add a little comment.
With the current code, once you click the “Export” button once, other controls will become unresponsive since WSS post-back will not work. You cannot export another copy neither. The following property assignment of the “Export” button is required for other post-back to work (including the “Export” button itself)
oBtn_Export.OnClientClick = “_spFormOnSubmitCalled = false;_spSuppressFormOnSubmitWrapper=true;”;
Cheers,
Kien
Comment from Harsh
Time April 16, 2010 at 2:37 pm
Hi, I am a beginner in Sharepoit 2007, I have an query regarding this post. how to create a button on sahrepoint list page (e.g. http://—-/allitems.aspx), if this is possible in sharepoint designer then how to call the webpart on clicking the button ‘Export to Excel’. please suggest me the way, it’s very urgent, I have to implement this
Thanks,
Harsh
Comment from G Vijai Kumar
Time April 20, 2010 at 5:21 am
@ Harsh: You can create a custom webpart which has only button, on button click you can execute the code above posted code.
Comment from Rittika
Time May 10, 2010 at 8:05 pm
Vijai, i tried to implement the above for a SharePoint list on (http://—-/allitems.aspx), but it gives me error – Object reference not set to an instance of an object.
Please advise.
Thanks.
Comment from PeteR
Time May 11, 2010 at 12:17 pm
To Kien Tran: Nice one!
I too am fairly new to SP2007 Development but had a more tricky issue. Rather than have a funky button to support the Export, I preferred to rather add a Verb to the Webpart such that the webpart dropdown menu renders the ‘Export File’ option; looks tidier.
1. Override the WebPartVerCollection
2. Create my new Verb :
WebPartVerb verb = new WebPartVerb(“AlertsReportExport”, OnExportClick, “_spFormOnSubmitCalled = false;_spSuppressFormOnSubmitWrapper=true;”);
3. Add it to the Verbs collection and then return it.
Cheers
Comment from Briana
Time May 24, 2010 at 5:07 pm
If I enable the grouping on SPGridview, will it also export with grouping?
Comment from Briana
Time May 24, 2010 at 6:29 pm
I tried without grouping, excel files is creating but nothing appearing in excel. let me know am I missing anything?
Comment from G Vijai Kumar
Time May 25, 2010 at 6:09 am
@ Briana: No, it won’t export with grouping even if you enable on SPGridView
Comment from G Vijai Kumar
Time May 25, 2010 at 6:10 am
@ Briana: Have you modified any code? if possible post your code, thanks
Comment from G Vijai Kumar
Time May 25, 2010 at 6:17 am
@ Rittika: Can you please post the error message, have you tried to debug the code, please provide me more information, thanks
Comment from Shankar Raman
Time May 25, 2010 at 3:21 pm
I am trying to export an spgridview that has a SPMenufield, however once exported the SPMenufield is not properly exported. I just get some hyperlinks which don’t make any sense. How do you “PrepareControlForExport” for SPMenuField?
Comment from Briana
Time May 30, 2010 at 8:39 am
@G Vijai Kumar
I am using your code in an aspx page with inline code. I used your code as it without changing anything and calling it on button click. It create a blank excel sheet thne I debug the code and noticed that it is not adding heading row as well not going in for-each loop. In my aspx page spgridview control is already added. I dont think it should be the problem. Secondly I also noticed that after executing the excelsheet If I try to re-click on buton, nothing happen.
Please advise






Comment from Cango
Time August 24, 2009 at 1:23 pm
This is really a great post, was very helpful.
In my case i have paging on, and when i export it only exports the 1st page but the pager contains more. Do you have an idea?