Wednesday, November 11, 2020

Export File (txt,csv) to SharePoint List using C#

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

There are always non-standard tasks in MS SharePoint server, one of such tasks is the export of data from the file (txt, csv) to the SharePoint list using C# to the example in the Event Receiver. Do not forget, when using the data array 'split' string [] arr = line.Split (';') specify a character that separates the values of your array.
Demonstration, download the link above:

1.CSV-file:

2.Code C#:
using Microsoft.SharePoint;
using System;

namespace EventDeployTest2.EventReceiver2
{
    public class EventReceiver2 : SPItemEventReceiver
    {
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            using (SPSite oSPsite = new SPSite("http://sharepoint/sites/test"))
            {
                using (SPWeb oSPWeb = oSPsite.OpenWeb())
                {
                    SPList list = oSPWeb.Lists["Test"];
                    string[] lines = System.IO.File.ReadAllLines(@"\\sharepoint\sites\test\SiteAssets\user.csv");
                    SPListItem itemToAdd = null;
                    foreach (string line in lines)
                    {
                        string[] arr = line.Split(';');
                        itemToAdd = list.Items.Add();
                        itemToAdd["Name"] = Convert.ToString(arr[0]);
                        itemToAdd["Surname"] = Convert.ToString(arr[1]);
                        itemToAdd["Department"] = Convert.ToString(arr[2]);
                        itemToAdd["Post"] = Convert.ToString(arr[3]);
                        itemToAdd["Position"] = Convert.ToString(arr[4]);
                        itemToAdd.Update();
                    }
                }
            }
        }
    }
}

3.Result (Export to SP List):

Happy Coding!

No comments:

Post a Comment