darknessomi/excellibrary

File with less than 100 rows causes corruption

Opened this issue · 1 comments

Following the sample on the homepage, the file created came out as corrupted. 
After a few trials, I found that the issue occurs when there are less than 100 
rows with added cells. A workaround is to add X additional rows with a blank 
cell if the number rows is less than 100.

Original issue reported on code.google.com by leandro....@gmail.com on 20 Mar 2014 at 3:53

I solve with this:

private static DataTable ConvetToDataTable<T>(List<T> data)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in Props)
            {
                dataTable.Columns.Add(prop.Name);
            }
            foreach (T item in data)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }

            if (data.Count() < 100)
            {
                var values = new object[Props.Length];
                for (int index = 0; index < 100 - data.Count(); index++)
                {
                    for (int i = 0; i < Props.Length; i++)
                    {
                        values[i] = " ";
                    }

                    dataTable.Rows.Add(values);
                }
            }

            return dataTable;
        }