Home » excel » C# and Excel, select column by name and get highest value

C# and Excel, select column by name and get highest value

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m quite new with c#, and with excel management too. I’m trying to do it with Microsoft.Office.Interop.Excel.
I have an excel file of this kind:

enter image description here

and what i want to do is open the file, read a column (i.e. x-com column) and get the highest number (in case of numbers, of course).

I opened the file with

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(fileName);
Excel.Worksheet xlWorksheet = xlWorkBook.Sheets[sheetNumber];
Excel.Range xlRange = xlWorksheet.UsedRange;

fileName and sheetNumber are the inputs of this method.

  • how can i read only one column? and get the highest number?
  • [optional] I am not sure what exactly is an Excel.Range. how can I print it on the console? what would look like the print if I print xlRange?
How to&Answers:

Edit:
I used the following libraryes:
using ExcelDataReader;
using ClosedXML.Excel;
I don’t really remember wich of the two libraryes I used but It probably is the second one.

You can try this code:

var file = new XLWorkbook("YOUR EXCEL FILE PATH");
           var foglio = file.Worksheet("sheet"); //select the worksheet
var firstRowUsed = foglio.FirstRowUsed(); //Gets the first row used
var ComuniRow = firstRowUsed.RowUsed(); //Gets the very first row used (in your case A1:"Control System")
var LastRow = LastRowUsed.RowUsed(); //Last Row used
ComuniRow = ComuniRow.RowBelow();//Select the row below (in your case A2:"P/M").
string Value = ComuniRow.GetString(); //Assigns "P/M" to the string 

Now you have the exact position of a field.
At this point you just have to cycle the whole column till the “LastRowUsed”.

while(ComuniRow != LastRow)
{
    string test = ComuniRow.GetString();//the value of the current selected cell
    ComuniRow = ComuniRow.RowBelow();
}

If you need to select a specific Column you can use .Cell(x)

while(ComuniRow.Cell([cell value]) != LastRow.Cell([cell value]))
{
    string test = ComuniRow.Cell([cell value]).GetString();//the value of the current selected cell
    ComuniRow = ComuniRow.RowBelow();
}