Parsing a .Net C# data class into Excel

I have a data class that is populated from a SQL Statement and I would like to easily parse into Excel. I won't always know how many property fields are in the data class in order to populate cell by cell so I'm looking for a higher level method to easily parse into Excel. Anyone have any ideas?
csalernoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

StephanLead Software EngineerCommented:
I used aspose.cells that generates excel files and it can import datatables.
0
Alexandre SimõesManager / Technology SpecialistCommented:
The excel file is a list of data or you have to fill only certain cells?

If it's for certain cells what I propose is to have custom placeholders on the cells you want to populate and replace them with the property fields of your class.

If you don't have a property field for a found place holder just clear the cell, otherwise replace by the property field value.

Example:
A placeholder could be: ${Name}
Search all cells and if you find one that contains ${ then it's a place holder, parse it, get the property field name, search on your data class if you have it and eather clean the cell or replace by the value.
0
Dennis AriesCEO @ Arkro ITCommented:
You forget to mention whether you want to parse it into an existing document or if you want to create a new document that can be opened using Excel.

For the latter one, the most easy way is using XML-Excel. Codeproject has a nice example for doing so. I use this technique a lot since it is a simple XML-file to create and can be openend by all clients I've encountered.

If you need to parse it into an existing closed document, I'd recommend using ADO

for instance:
string fileName = @"D:\test.xlsx"; 
string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;" + 
        "Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=0'", fileName); 

using(OleDbConnection cn = new OleDbConnection(connectionString))
{
    cn.Open();
    OleDbCommand cmd1 = new OleDbCommand("INSERT INTO [Sheet1$] " + 
         "([Column1],[Column2],[Column3],[Column4]) " + 
         "VALUES(@value1, @value2, @value3, @value4)", cn);
   cmd1.Parameters.AddWithValue("@value1", "Key1");
   cmd1.Parameters.AddWithValue("@value2", "Sample1");
   cmd1.Parameters.AddWithValue("@value3", 1);
   cmd1.Parameters.AddWithValue("@value4", 9);
   cmd1.ExecuteNonQuery();
}

Open in new window


If the document is opened, use Excel-Automation to fill the cells you require.
Some examples can be found at NetInformations.com.
0
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

csalernoAuthor Commented:
All good info.
But what I'm really looking for is a non-third party way to parse a List<T> of data classes thru Excel Automation. I have all of the code, just missing a clean way of parsing. Some of my data classes have a couple hundred properties.
0
StephanLead Software EngineerCommented:
Well, you can convert a List<T> to a DataTable but it must not container nullable parameters like Nullable<int> (int?), Nullable<DateTime> etc..

public class ListtoDataTableConverter
    {
        public DataTable ToDataTable<T>(List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);
            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name);
            }
             foreach (T item in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }
             //put a breakpoint here and check datatable
            return dataTable;
        }
    }

Open in new window


Please note that this is not performance friendly, there are third party libraries that will have better performance like Vanilla, Hyper
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
csalernoAuthor Commented:
Thanks for the code that worked perfectly.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.