Pages

March 10, 2014

Exporting to excel from a custom class object using C#.NET

We may face a scenario to export the data of custom class object to excel using InterOp.You can get the property name's from the class object using Reflection.Create a work sheet header by reading the each propety of the class object.I have created a separate method to get the all properties into a list collection of string as given below

        ///


        /// Get the list of Properties Name into a list collection.
        ///

        ///
        ///
        public List GetPropeties(Employee objEmployee)
        {
            Type myType = objEmployee.GetType();
            IList props = new List(myType.GetProperties());
            List lstPropertiesNames = new List();

            foreach (PropertyInfo prop in props)
            {
                lstPropertiesNames.Add(prop.Name);
            }
            return lstPropertiesNames;
        }

We need to call this method to create the worksheet header's as given beloe
                List lstProperties = GetPropeties(new Employee());
                Char x = 'A';
                foreach (String eachProperty in lstProperties)
                {
                    // ------------------------------------------------
                    // Creation of header cells
                    // ------------------------------------------------
                    workSheet.Cells[1, x.ToString()] = eachProperty;
                    x = (Char)(Convert.ToUInt32(x) + 1);
                }