Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
355
How to find last used column in excel file?
posted

Hello,

I need to iterate worksheet columns collection in code but i need to know the last used column in worksheet.

Could you advise me how to find last used column?

my code example:

using Infragistics.Documents.Excel;
...
for (int i = 0; i < lastUsedColumn; i++)
{
...
}

before I used Worksheets[0].Columns collection but it skipped some columns in worksheet.


foreach(var column in workbook.Worksheets[0].Columns) 
{
...
}


Thank you

Libor

Parents
  • 44743
    posted

    The Columns collection is a lazily loaded collection. WorksheetColumn instances are only created when they are requested. When loading a workbook from a file, the Excel library will internally request the columns so they can be populated with width and formatting information (if they are not default values). When you iterate over the Columns collection with a foreach loop, you are just iterating the already created columns. When you iterate over the collection with a for loop and therefore request the columns in order, you are forcing them to get created. What you could do is use a foreach loop to determine the last created column, then use a for loop to iterate from column 0 to that column. However, you should know that the columns do not hold any cell data. That is owned by the rows. So it is possible that no columns have been created even though the worksheet has data. What are you trying to do by iterating the columns?

Reply Children