Thursday 21 November 2013

Programmatically Export data from SharePoint List to Excel SpreadSheet

Hi All,
 Today I will give you the code for exporting data from SharePoint List to Excel.

Ok Without delay, directly going to the code...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Data;
using System.IO;
using System.Web.UI;

namespace Excel
{
    class Program
    {
        private static DataTable dataTable;
        private static SPList list;

        static void Main(string[] args)
        {
            try
            {
                SPSite Osite = new SPSite("http://wf13staging.myhcl.com/sites/BPRCreatives/Creative%20CR%20Tracker");
                SPWeb oWeb = Osite.OpenWeb();
                string _siteUrl = oWeb.Url.ToString();
                if (!string.IsNullOrEmpty(_siteUrl))
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(oWeb.Url))
                        {
                            if (site != null)
                            {
                                SPWeb web = site.OpenWeb();
                                if (web != null)
                                {
                                    #region Export List
                                    string _listName = "Excel List"; // Name of your List
                                    if (!string.IsNullOrEmpty(_listName))
                                    {
                                        list = web.Lists["Excel"];
                                        if (list != null)
                                        {
                                            dataTable = new DataTable();
                                            InitializeExcel(list, dataTable);
                                            string _schemaXML = list.DefaultView.ViewFields.SchemaXml;

                                            if (list.Items != null && list.ItemCount > 0)
                                            {
                                                foreach (SPListItem _item in list.Items)
                                                {
                                                    DataRow dr = dataTable.NewRow();
                                                    foreach (DataColumn _column in dataTable.Columns)
                                                    {
                                                        if (dataTable.Columns[_column.ColumnName] != null && _item[_column.ColumnName] != null)
                                                        {
                                                            dr[_column.ColumnName] = _item[_column.ColumnName].ToString();
                                                        }
                                                    }
                                                    dataTable.Rows.Add(dr);
                                                }
                                            }
                                        }
                                    }
                                    System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
                                    grid.HeaderStyle.Font.Bold = true;
                                    grid.DataSource = dataTable;
                                    grid.DataBind();
          // U can modify the name of the excel file according to ur wish :)

                                    using (StreamWriter streamWriter = new StreamWriter(@"F:\Chandra\Excel" + list.Title + ".xls", false, Encoding.UTF8))
                                    {
                                        using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(streamWriter))
                                        {
                                            grid.RenderControl(htmlTextWriter);
                                        }
                                    }

                                    #endregion
                                }
                            }
                        }
                    });
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }

        public static void InitializeExcel(SPList list, DataTable _datatable)
        {
            if (list != null)
            {
                string _schemaXML = list.DefaultView.ViewFields.SchemaXml;
                if (list.Items != null && list.ItemCount > 0)
                {
                    foreach (SPListItem _item in list.Items)
                    {
                        foreach (SPField _itemField in _item.Fields)
                        {
                            if (_schemaXML.Contains(_itemField.InternalName))
                            {
                                if (_item[_itemField.InternalName] != null)
                                {
                                    if (!_datatable.Columns.Contains(_itemField.InternalName))
                                    {
                                        _datatable.Columns.Add(new DataColumn(_itemField.StaticName, Type.GetType("System.String")));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}



That's it... Directly paste the code and Ur work is done.... ;)

Monday 11 November 2013

SPListItem.Delete() Vs SPListItem.Recycle()

Hi All,
Good Day. Hope u all are doing good. Today we will see about 2 ways of deleting an item programmatically, which ofcourse are significant on their own ways.

While doing coding , 
SPListItem.Delete() is the most used method to delete an item. There is one more method - SPListItem.Recycle().

SPListItem.Recycle() :
When we use this method, the item gets moved to the Recycle Bin. So that , it can be restored if needed.

SPListItem.Delete() :
When we use this method, the item gets permanently deleted.

Under the hood :

Internally there isn’t much difference between the SPListItem.Delete and SPListItem.Recycle methods. Both call an internal SPListItem.Delete method with a different parameter which determines whether an item should be moved to the Recycle Bin or permanently deleted.


public override void Delete()   
{   
      if (this.HasExternalDataSource)   
      {   
            SPUtility.ValidateFormDigest();   
            string bdcid = (string) ((string) this.GetValue("BdcIdentity"));   
            this.ParentList.DataSource.DeleteItem(bdcid);   
      }   
      else   
      {   
            this.DeleteCore(DeleteOp.Delete);   
      }   
}   
public System.Guid Recycle()   
{   
      if (this.HasExternalDataSource)   
      {   
            SPExternalList.ThrowNotSupportedExceptionForMethod("Recycle", base.GetType());   
      }   
      return this.DeleteCore(DeleteOp.Recycle);   

}   

I hope you will be getting a good use of Recycle method in your forthcoming challenges.

Thanks for reading.