Wednesday, November 11, 2020

Export List Items (MS SharePoint) to MS SQL server Database table using C#(CSOM)

Due to the closure of "the blog TechNet" I transfer all my articles in the blog :)

When developing a new project, I needed to download the data from the MS SharePoint list to the MS SQL Server table, where I used C#(CSOM). This code is preferable for me, flexible and not too resource-intensive, as a rule I use it for events by Custom Timer Job, but I am also sure that he is approaching the example and for Event Reciever and other opportunities. To work with C#(CSOM), use namespace (reference) Microsoft.SharePoint.Client.
ClientContext context = new ClientContext("http://sp/sites/test");
Web web = context.Web;
List list = context.Web.Lists.GetByTitle("DataList");
context.Load(list);
context.ExecuteQuery();
CamlQuery query = new CamlQuery();
query.ViewXml = "";
ListItemCollection allitems = list.GetItems(query);
context.Load(allitems);
context.ExecuteQuery();
SqlConnection cn = new SqlConnection();
DataSet EmpDataSet = new DataSet();
SqlDataAdapter da;
cn.ConnectionString = @"Data Source=SQLServer;Initial Catalog=DataTable;Integrated Security=SSPI";
cn.Open();
da = new SqlDataAdapter("select * from [dbo].[Table_Data]", cn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Fill(EmpDataSet, "Table_Data");
DataTable table = EmpDataSet.Tables[0];
foreach (ListItem listitem in allitems)
{
    DataRow row = table.NewRow();
    row["Date"] = System.TimeZone.CurrentTimeZone.ToLocalTime(Convert.ToDateTime(listitem["Created"].ToString()));
    row["Column1"] = listitem["Title"].ToString();
    row["Column2"] = listitem["Event1"].ToString();
    row["Author"] = listitem["AuthorPosition"].ToString();
    row["DateToday"] = System.TimeZone.CurrentTimeZone.ToLocalTime(Convert.ToDateTime(listitem["Today"].ToString()));
    table.Rows.Add(row);
    builder.GetInsertCommand();
}
da.Update(EmpDataSet, "Table_Data");

Happy Coding!

No comments:

Post a Comment