Jayant Varshney
Jayant Varshney

Reputation: 1825

Using LINQ with Open XML (Excel)

I have an excel sheet and I am processing it by using Open XML SDK 2.0. The scenario is, There is a column which contains date in my excel sheet. I need to get the maximum and minimum date from that column.

I can do this by looping and reaching to that cell, doing comparisons and finding desired answer.

But due to optimality I want to do this by using LINQ to get Minimum and maximum dates.

Is it possible to do so? If yes, then how?

Upvotes: 2

Views: 4632

Answers (4)

Jayant Varshney
Jayant Varshney

Reputation: 1825

Thanks to all

I have used like this

IEnumerable<Cell> cells = workSheetPart.Worksheet.Descendants<Cell>().Where(c => string.Compare(GetColumnName(c.CellReference.Value), strIndex, false) == 0).OrderBy(c => c.CellValue.Text);

And getting min and max values like this

int cellCount = cells.Count();
Cell MaxCell = cells.ToArray()[0];
Cell MinCell = cells.ToArray()[cellCount - 1];

Upvotes: 1

Dmitry Pavlov
Dmitry Pavlov

Reputation: 28320

You could read this post Open XML SDK and LINQ to XML by Eric White (Eric wrote a lot of posts about OpenXML and LINQ). And then you will be able to query your Excel file data with LINQ. You might want to see the spreadsheet objects structure in The Open XML SDK Productivity Tool, which can generate the source code for you. You could use this code to understand how to programmatically access the data you need.

Upvotes: 0

Bryan Crosby
Bryan Crosby

Reputation: 6554

You will want to take a look at the LINQ Min() and Max() functions. If you need to return the entire Cell object, you can use OrderByDescending().

Upvotes: 0

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

You can see how to get IEnumerable of all cells from column there:Read excel sheet data in columns using OpenXML, and use Max() on it.

Upvotes: 1

Related Questions