15/12/2012

CRM Dynamics 2011 - Loading data from csv File

There are many ways to load external data and pump it to CRM dynamics. The following is a convenient way of loading a csv file (Accounts) and import them into CRM Dynamics 2011 Accounts entity:

Loading the CSV file into a DataTable

The following method accepts a csv file name and directory, load the data using odbc connection to the file and returns a DataTable
        
public static DataTable GetDataTableForCSV(string csvDirectory, string csvFileName)
        {

            OdbcConnection dbConn = new OdbcConnection("Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=" + csvDirectory + ";");
            dbConn.Open();
            string dbName = "[" + csvFileName + "]";
            string sql = @"select * from " + dbName;
            OdbcDataAdapter dbCmd = new OdbcDataAdapter(sql, dbConn);
            DataSet dataSet = new DataSet(dbName);
            dbCmd.Fill(dataSet, dbName);
            dbConn.Close();
            return dataSet.Tables[0];
        
        }
 

Load the data into MS CRM Dynamics 2011 Accounts

The following is a sample of importing accounts from csv file into MS Dynamics 2011 assuming you have already built your OrganizationServiceProx (_service in this sample)

        static  void Main(string[] args)
        {

            //Creation of Organization Service porxy is omited for simplicity
            DataTable accounts = GetDataTableForCSV("C:\\MyCSVFile\\Sample\\","accounts.csv");

            //we have loaded the data from csv into accounts DataTable
            // lets iterate through and add them to our CRM Account entity
            foreach (DataRow rowItem in accounts.Rows)
            {
                Entity account = new Entity("account");
                account.Attributes["name"] = rowItem["Name"];
                _service.Create(account);
            }

            Console.WriteLine("Click  to continue");
            Console.Read();

        }

2 comments:

  1. ERROR [42S02] [Microsoft][ODBC Text Driver] The Microsoft Jet database engine could not find the object 'accounts.csv'. Make sure the object exists and that you spell its name and the path name correctly.

    ReplyDelete
  2. Eren, i think you need to check if you have account.csv file copied into "C:\\MyCSVFile\\Sample\\" folder for this sample to work

    ReplyDelete