Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Fetch Column Data from Excel sheet

(1) ShareShare
ReportReport
Posted on by

Hello ,

I am trying to fetch column value from excel sheet and map those values in respective fields in CRM Programatically  . Can anyone help ??

*This post is locked for comments

  • Pratima Profile Picture
    Pratima on at
    RE: Fetch Column Data from Excel sheet

    I am not taking excel sheet from desktop or any folder ...i am attaching excel in note entity ,From where how to get path of excel ?

  • Suggested answer
    Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,205 on at
    RE: Fetch Column Data from Excel sheet

    Hi Pratima,

    Below is the code that i have used for updating user business unit, reading it from excel file, for this you need to create a console application in .Net and paste the below code in program.cs file, and change the entity that you want to udpate

    *****************************************************************

    using Microsoft.Crm.Sdk.Messages;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Client;

    using System;

    using System.Collections.Generic;

    using System.Configuration;

    using System.Data;

    using System.Data.OleDb;

    using System.IO;

    using System.Linq;

    using System.ServiceModel.Description;

    using System.Text;

    using System.Threading.Tasks;

    namespace UpdateBusinessUnitOfUserInCRM

    {

       class Program

       {

           static void Main(string[] args)

           {

               TextWriter tw = File.CreateText(@"D:\Log\BusinessUnit.txt");

               try

               {                

                   DateTime date = DateTime.Now;

                   tw.WriteLine("Console Last Start Time : " + date.ToString("dd/mm/yyyy HH:mm"));

                   // Creating client Credential object for setting username and password

                   ClientCredentials _crmCredentials = new ClientCredentials();

                   // Orginization Service URL

                   Uri _organizationUri = new Uri(ConfigurationManager.AppSettings["Url"]);

                   //Providing UserName and Password

                   _crmCredentials.UserName.UserName = ConfigurationManager.AppSettings["Username"];

                   _crmCredentials.UserName.Password = ConfigurationManager.AppSettings["Password"];

                   // Creating connection with dynamics crm

                   using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(_organizationUri, null, _crmCredentials, null))

                   {

                       DataTable dt = ImportData();

                       if (dt.Rows.Count > 0)

                       {

                           for (int i = 0; i < dt.Rows.Count; i++)

                           {

                               Console.WriteLine("Count :" + i);

                               tw.WriteLine(i.ToString() + ") Last Record executed : " + dt.Rows[i]["User Unique ID"].ToString());

                               // get userid and business unit id from Excel

                               string UserID = dt.Rows[i]["User Unique ID"].ToString();

                               string BusinessUnitID = dt.Rows[i]["New Business Unit Unique ID"].ToString();

                               // check if userID and BusinessUnitID is not empty

                               if (!string.IsNullOrEmpty(UserID) && !string.IsNullOrEmpty(BusinessUnitID))

                               {

                                   // Creating IOrganizationService object to access organization services              

                                   IOrganizationService service = _serviceProxy;

                                   SetBusinessSystemUserRequest req = new SetBusinessSystemUserRequest();

                                   //business unit to assign user to

                                   req.BusinessId = new Guid(BusinessUnitID);

                                   //user to re-assign

                                   req.UserId = new Guid(UserID);

                                   //can be a different team or systemuser, used to reassign records owned by person

                                   req.ReassignPrincipal = new EntityReference("systemuser", new Guid(UserID));

                                   // Executing service request

                                   SetBusinessSystemUserResponse resp = (SetBusinessSystemUserResponse)service.Execute(req);

                                   string res = resp.Results.ToString();

                               }

                           }

                       }

                   }

                   tw.WriteLine("Console Last End Time : " + date.ToString("dd/mm/yyyy HH:mm"));

                   tw.WriteLine("==============================================================");

                   tw.Close();

               }

               catch (Exception ex)

               {                

                   tw.Close();

                   throw ex;

               }

           }

           public static DataTable ImportData()

           {

               DataTable dt = new DataTable();

               string filepath = "C:\\Users\\shahbaaza\\Desktop\\Update Business unit.xlsx";

               string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\";Persist Security Info=False;";

               OleDbConnection connExcel = new OleDbConnection(connString);

               OleDbCommand cmdExcel = new OleDbCommand();

               OleDbDataAdapter oda = new OleDbDataAdapter();

               cmdExcel.Connection = connExcel;

               //Get the name of First Sheet

               connExcel.Open();

               DataTable dtExcelSchema;

               dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

               string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();

               connExcel.Close();

               //Read Data from First Sheet

               connExcel.Open();

               cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";

               oda.SelectCommand = cmdExcel;

               oda.Fill(dt);

               connExcel.Close();

               return dt;

           }

       }

       //ImportData method used in UploadData Button click

    }

    *****************************************************************

    Best Regards,

    Shahbaaz

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,516 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,409 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans