Wednesday, July 3, 2013

Export User profiles into Excel Sheet Using User Profile Service

In this post i am going to show how to export user profiles of sharepoint 2010/2013 to Excel sheet. normally we export User profiles for analysis purpose or comparison purpose.

If you want to retrieve all the User profiles from Sharepoint 2010 or 2013 server, you can use profileManager (ServerObjectModel) or UserprofileService(.asmx service). Here i am going to use .asmx service.

1. Create a Console project in Visual Studio and named it as ExportUPSToExcel

2. Add user profile service as Web Service Reference and name it as ProdUPS


3. Refer the service in .cs file
    using ExportUPSToExcel.ProdUPS;

4. Copy and paste following code into program.cs (or create new .cs file , in my case it is ExportUPS.cs  ) file

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

namespace ExportUPSToExcel
{
    public class ExportUPS
    {
        static void Main(string[] args)
        {
            ExportToExcel();
        }

        static void ExportToExcel()
        {
                Console.WriteLine("Accessing User profile Service.......");

                StringBuilder sb = new StringBuilder();
            
                //Creating headers in the first row

                //Loop through all the user profiles in the sharepoint database
                Console.WriteLine("Starting to Connect.......");

                ProdUPS.UserProfileService ups = new VplusProdUPS.UserProfileService();
                System.Net.NetworkCredential nc = new System.Net.NetworkCredential("adminUserName", "AdminPassword", "DomainName");
                ups.PreAuthenticate = false;
                ups.Credentials = nc;
                Console.WriteLine("Starting ........");
                long count = ups.GetUserProfileCount();
                int inteIndex = 0;
                VplusProdUPS.PropertyData[] properties; 
            
                GetUserProfileByIndexResult  p = ups.GetUserProfileByIndex(-1); // gets the first profile on the list
                int k = 0;
                while (p.UserProfile != null)
                { 
                    // do what you want with the User Profile
                    properties = p.UserProfile;
                    Console.WriteLine("Processing: " + k.ToString());
                    // update the columns name - first row
                    if (k == 0)
                    {
                        for (int i = 0; i < properties.Length; i++)
                        {                         
                                sb.Append(properties[i].Name + ",");
                            
                            
                        }
                        sb.Append("\r\n");
                    }
                    // update the values into appropriate columns
                    for (int m = 0; m < properties.Length; m++)
                    {
                        StringBuilder value = new StringBuilder();                      
                            //continue;
                            if (properties[m].Values.Length == 0)
                            {
                                value.Append("" + ",");
                            }
                            else    // if the field has more than one value
                            {
                                for (int j = 0; j < properties[m].Values.Length; j++)
                                {
                                    if (properties[m].Values[j].Value != null)
                                    {
                                        if (j == 0)
                                        {
                                            value.Append(properties[m].Values[j].Value);
                                        }
                                        else
                                        {
                                            value.Append("&" + properties[m].Values[j].Value);
                                        }
                                    }
                                    else
                                    {
                                        if (j == 0)
                                        {
                                            value.Append("");
                                        }
                                        else
                                        {
                                            value.Append("&" + "");
                                        }
                                    }

                                }
                                value.Append(",");
                            }
                            sb.Append(value);                       
                    }
                    sb.Append("\r\n");
                    // get the next value for index
                    int nextValue;
                    bool res = int.TryParse(p.NextValue, out nextValue);
                    p = ups.GetUserProfileByIndex(nextValue);
                    k++;
                }

                Console.WriteLine("Finished profile retrieval");
                Console.WriteLine("Writing to csv file");
                Console.WriteLine("Total User Profiles :" + count.ToString());

                //Write the long string to a csv file and save it to the desktop

                TextWriter tw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + "UPS2010Final1.csv");
                tw.WriteLine(sb.ToString());
                tw.Close();

        }
    }
}

Replace "adminUserName", "AdminPassword", "DomainName" with appropriate values. but this account should have enough permission to read and retrieve the user profiles from Sharepoint server.

5. Run the application and check the console for progress status

6. finally open the excel sheet and check the fields.


Notes :
  • If any fields has value with comma(",") replace with other characters before write to excel since it creates new columns in excel.
  • Don't use For loop for iteration. sometimes it will give duplicate entries. More details refer this article