Home > OS >  Using C# to get the value of column name that includes a certain string
Using C# to get the value of column name that includes a certain string

Time:02-02

I have a program I am writing that is to read an excel file and extract from it any column names that contain the string "Zone_" in them. This is the code I have written using C# and ClosedXML

                        // Read the excel file
                        var workbook = new XLWorkbook(file);
                        var worksheet = workbook.Worksheet(1);
                        zonesColumns = worksheet.Columns()
                            .Where(c => c.FirstCell().Value.ToString().StartsWith("Zone_"))
                            .ToList();

the problem I am running into is that instead of getting the Column name I am getting a bunch of jibberish instead. I am not sure what I did wrong within the code as to me it seems to do what I want it to. Thanks for the help!

CodePudding user response:

Your query as shown is retrieving columns. A column is described as a range something like Sheet1!A1:A1048576 (is this what you mean by jibberish)?

But if I'm following, you want the names. Try getting a collection of the first cells of the retrieved columns, then select the GetText() result.

var names = 
    worksheet
    .Columns()
    .Select(col=>col.FirstCell())
    .Select(cell=>cell.GetText())
    .Where(name=>name.StartsWith("Zone_"))
    .ToList();
  • Related