Share Point List View to Excel using C#

Step 1: Create a visual webpart
Step 2: Add a button to the webpart
Step 3: Write the below code in button click event
 
Note: Only you have to pass list name and view name, That’s it
 
 
protected void btnExport_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using(SPSite site=new SPSite(SPContext.Current.Web.Url))
                {
                    using(SPWeb web=site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        string values = string.Empty;
                        SPList list = web.Lists["List Name"];
                        SPView view = list.Views["List View Name"];
                        SPListItemCollection items = list.GetItems(view);
                        DataTable dt = new DataTable();
                        StringCollection viewFields = view.ViewFields.ToStringCollection();
                        foreach (string cols in viewFields)
                        {
                            dt.Columns.Add(list.Fields.GetFieldByInternalName(cols).Title.ToString());
                        }
                        foreach (SPListItem item in items)
                        {
                            DataRow dr = dt.NewRow();
                            foreach (string fieldName in viewFields)
                            {
                                values += item[fieldName] + ",";
                            }
                            values = values.TrimEnd(values[values.Length - 1]);
                            string[] exceptionValues = values.Split(',');
                            dt.Rows.Add(exceptionValues);
                            values = string.Empty;
                        }
                        this.ExporttoExcel(dt);
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
 
 
// Add the below Custom method to export the data table values to excel
 
private void ExporttoExcel(DataTable dt)
        {
            try
            {
                string str = "ExceptionRequestReport "+System.DateTime.Now+".xls";
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("Content-Disposition""attachment; filename=" + str);
                Response.ContentType = "application/vnd.ms-excel";
                EnableViewState = false;
                StringWriter writer = new StringWriter();
                HtmlTextWriter writer2 = new HtmlTextWriter(writer);
                DataGrid grid = new DataGrid { DataSource = dt };
                grid.DataBind();
                grid.HeaderStyle.Font.Bold = true; ;
                grid.RenderControl(writer2);
                Response.Write("<style> TABLE { border:groove 1px #999; } " +
                                    "TD { border:groove 1px #D5D5D5; text-align:center } </style>");
                base.Response.Write(writer.ToString());
                base.Response.End();
            }
            catch (Exception)
            {
               
            }
        }

Comments

Post a Comment

Popular posts from this blog

SharePoint 2013 Keyword Query (KQL) Content Class Property Restrictions

Filtering the Sharepoint List Taxonomy Column using Rest API