How to find column id by cell value?

2019-06-21 19:55发布

问题:

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.

回答1:

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());
}