Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find column id by cell value?

I have a huge excel file and would like to find column "ID" for later use. Row 1 is empty, header rows is in the second.

int ID_Number = ((Range)sheet.get_Range("A2", sheet.UsedRange.Columns.Count).Find("ID Number", Missing.Value, XlFindLookIn.xlValues, XlLookAt.xlPart, XlSearchOrder.xlByColumns, XlSearchDirection.xlNext, true, Missing.Value, Missing.Value) ).Column;
int Size = ((Range)sheet.get_Range("A2", sheet.UsedRange.Columns.Count).Find("Size", Missing.Value, XlFindLookIn.xlValues, XlLookAt.xlPart, XlSearchOrder.xlByColumns, XlSearchDirection.xlNext, true, Missing.Value, Missing.Value) ).Column;

Unhandled Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800A03EC

Sometimes the columns order is changing in the excel and would like to handle it dinamically and not by defining column M eg for Size.

like image 329
szabieable Avatar asked Nov 14 '13 09:11

szabieable


1 Answers

Is this what you are trying? (TRIED AND TESTED in VS 2010 + Excel 2010)

object misValue = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.get_Range("A2", "A2");

Microsoft.Office.Interop.Excel.Range xlFound = xlRange.EntireRow.Find("ID Number",
misValue, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlNext, 
true, misValue, misValue);

//~~> Check if a range was returned
if (!(xlFound == null))
{
    int ID_Number = xlFound.Column;
    MessageBox.Show(ID_Number.ToString());
}
like image 116
Siddharth Rout Avatar answered Sep 29 '22 18:09

Siddharth Rout