web
You’re offline. This is a read only version of the page.
close
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

I have the same question (0)
  • Suggested answer
    Shahbaaz Ansari Profile Picture
    6,211 on at

    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

  • Pratima Profile Picture
    on at

    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 ?

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans