Export to Excel in SharePoint 2010
private DataTable SearchItem()
{
DataTable dt = new DataTable();
SPSecurity.RunWithElevatedPrivileges(delegate
{
SPList list = SPContext.Current.Web.Lists["TestList"];
string query = null;
SPQuery qry = new SPQuery(list.DefaultView);
//SPListItemCollection lstColl =
int iCnt = 0;
try
{
qry.ViewFields = "<FieldRef Name='LinkTitleNoMenu' /><FieldRef Name='TestColumn' />";
qry.Query = query;
dt= list.GetItems(qry).GetDataTable();
}
catch (Exception ex) { Response.Write(ex.Message); }
});
return dt;
}
private void ExportToExcel1()
{
DataTable dt1 = SearchItem();
gvdetails.DataSource = dt1;
gvdetails.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ExcelReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvdetails.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
<asp:GridView runat="server" ID="gvdetails" Width="100%" AllowPaging="false" PageSize="1000" AllowSorting="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="Black" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Add script to placeholdermain
<script type="text/javascript">
_spOriginalFormAction = document.forms[0].action;
_spSuppressFormOnSubmitWrapper = true;
</script>
No comments:
Post a Comment