SharePoint CSOM to Create Folders and Sub Folders based on Excel Data

Contents:

1. Reading data from the Excel sheet.
2. Connecting to SharePoint Online Site & Checking the SharePoint list is available or not.
3. Creating the SharePoint Library Folders and Sub Folders.
4. Conclusion.

1. Reading data from the Excel sheet:

a. Open Visual Studio, Select New Project Creation and Select C# Console application and provide the appropriate Solution name.
b. First add the required references like below.
    I . using Microsoft.SharePoint.Client;
    II. using System.Configuration; (Used to read the data from the App.config file)
    III. using Microsoft.Office.Interop.Excel; (Excel supported file reference)

   Note: If above references and not able to add please install the references from the NuGet Package  Manager Console.

To Read the values from the App.config file use the below  and declare all the fields globally for re-usability.

               public static string userName = ConfigurationManager.AppSettings["Username"];
        public static string userPassword = ConfigurationManager.AppSettings["Password"];
        public static string siteURL = ConfigurationManager.AppSettings["SiteURL"];
        public static string libName = ConfigurationManager.AppSettings["LibraryName"];
        public static string excelFilePath = ConfigurationManager.AppSettings["ExcelFilePath"];
        public static string fileExt = string.Empty;
        OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();

//To Read Excel data
        public void _readExcelData(ClientContext clientCtx, List list)
        {
            fileExt = Path.GetExtension(excelFilePath); //get the file extension
            if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)
            {
                try
                {
                    //Create COM Objects. Create a COM object for everything that is referenced
                    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                    Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(excelFilePath);
                    Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
                    Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;

                    var rowCount = xlRange.Rows.Count;
                    var colCount = xlRange.Columns.Count;

                    Console.WriteLine("Rows Count: " + rowCount + ", Column Count : " + colCount);

                    //iterate over the rows and columns and print to the console as it appears in the file
                    //excel is not zero based!!
                    for (int i = 1; i <= rowCount; i++)
                    {
                        Console.Write(xlRange.Cells[i, 1].Value2.ToString() + "\t");
                        Console.Write(xlRange.Cells[i, 2].Value2.ToString() + "\t");
                        Console.Write("\r\n");
                        string mainFolder = "";
                        string subFolders = "";
                        if (xlRange.Cells[i, 1].Value2.ToString() != "MainFolder" && xlRange.Cells[i, 2].Value2.ToString() != "SubFolders")
                        {
                            mainFolder = xlRange.Cells[i, 1].Value2.ToString();
                            subFolders = xlRange.Cells[i, 2].Value2.ToString();
                            _createLibraryFolders(clientCtx, list, mainFolder, subFolders);
                        }
                    }
                }
                catch (Exception excel)
                {
                    Console.WriteLine("Eccel Error: " + excel.Message);
                }
            }
        }



2. Connecting to SharePoint Online Site & Checking the SharePoint list is available or not

//Function is to check list is available in the current sire or not
        public void _checkListAvailbleinSite()
        {
            try
            {
                using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL, userName, userPassword))
                {
                    ListCollection listCollection = clientContext.Web.Lists;
                    clientContext.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == libName));
                    List oList = clientContext.Web.Lists.GetByTitle(libName.Trim());
                    clientContext.ExecuteQuery();
                    if (listCollection.Count > 0)
                    {
                        Console.WriteLine(libName + " List is available in the site");
                        _readExcelData(clientContext, oList);
                    }
                    else
                    {
                        Console.WriteLine(libName + " Lsit is not available in the site");
                    }
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }

3. Creating the SharePoint Library Folders and Sub Folders:


//Function is used to create folders and sub folders in the specified list
        public void _createLibraryFolders(ClientContext clientCtx, List list, string mainFolder, string subFolders)
        {
            bool isFolderExists = list.RootFolder.FolderExists(mainFolder.Trim());
            string[] strsubFolders = subFolders.Trim().Split(',');
            Folder folder;
            string topFolderServerURL = "";
            
            //If Top folder is not available creating Top Folder and Sub Folders
            if (!isFolderExists)
            {
                folder = list.RootFolder.CreateFolder(mainFolder.Trim());
                clientCtx.Load(folder);
                clientCtx.ExecuteQueryRetry();
                topFolderServerURL = folder.ServerRelativeUrl;

                if (subFolders != "")
                {
                    for (int i = 0; i < strsubFolders.Length; i++)
                    {
                        //The function is used to create folder and subfolder at a time once.
                        Folder folder1 = folder.CreateFolder(strsubFolders[i]);
                        clientCtx.ExecuteQueryRetry();
                        Console.WriteLine("Subfolder is created: " + strsubFolders[i] + ", Top folder name: " + mainFolder.Trim());
                    }
                }
            }
            //If Top Folder is available Creating the Sub Folders
            else
            {
                // Retrieves and Creates Folder if not exists  
                Folder existfolder = list.RootFolder.EnsureFolder(mainFolder.Trim());

                if (subFolders.Trim() != "")
                {
                    for (int i = 0; i < strsubFolders.Length; i++)
                    {
                        try
                        {
                            if (!existfolder.FolderExists(strsubFolders[i]))
                            {
                                //The function is used to create folder and subfolder at a time once.
                                Folder folder1 = existfolder.CreateFolder(strsubFolders[i]);
                                clientCtx.ExecuteQueryRetry();
                                Console.WriteLine("Subfolder is created: " + strsubFolders[i] + ", Top folder name: " + mainFolder.Trim());
                            }
                        }
                        catch (Exception exc1)
                        {
                            Console.WriteLine(exc1.Message);
                        }

                    }
                }

            }
        }

4. Conclusion.

On Page load first we will check the list is available or not and after we will call the Read Excel data function and for each row in excel we will create the Folders and Sub Folders.

                                                Sharing is caring.... Enjoy SharePoint Coding.....





Comments

Popular posts from this blog

SharePoint 2013 Keyword Query (KQL) Content Class Property Restrictions

Filtering the Sharepoint List Taxonomy Column using Rest API