GemBox Support Forum

ExcelWorksheet.Columns.Count returns 0

I have this method that is called twice:

CreateExcelHeader(ExcelWorksheet ws, ref string[] aExcelHeader, ref int iColumn, int iRow)

The second time in this method I try to get a column count:

iColumn = ws.Columns.Count;

I’m returned ZERO.

I’m not getting any error or warnings when I call the method the second time. The previous time I do an ef.Save(Globals.sXLSFile);
I reopen the Excel file again to be sure the data is saved.

What am I doing wrong?

In troubleshooting found if I try to count any worksheet created by my code the column count is 0. But if i modify the workbook/sheet with data it does count the columns.

More confused.

When I go back and alter the worksheet created by my gembox code now the column count works.
Alter by setting the Data or changing font size and saving in excel.

Hi Herb,

This is by design due to performance reasons; the cells are internally allocated in rows and not in columns.
The ExcelColumn objects are created only if they have a non-standard width or style, or if they are accessed directly.
Please check the remarks of the ExcelWorksheet.Columns property.

To find the last column that’s occupied with a data, you can use the ExcelWorksheet.CalculateMaxUsedColumns method:
Like this:

iColumn = ws.CalculateMaxUsedColumns();

I hope this helps.