My application is reading the excel file data using Interop libraries.My code is below.
string filepath = "C:\\SAddresses.xls";
XLApp=new Excel.Application();
XLBook = XLApp.Workbooks.Open(filepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
XLSheet = (Excel.Worksheet)XLBook.Worksheets.get_Item(1);
cRange = XLSheet.UsedRange;
for (int rowcnt = 2; rowcnt < cRange.Rows.Count; rowcnt++)
{
for (int colidx = 1; colidx < cRange.Columns.Count; colidx++)
{
colvalue+=((cRange.Cells[rowidx,colidx] as Excel.Range).Value2);
}
}
In the above I am able to get the data using each row index and column index.But I want to read the column data using column name instead of column index.How to do this.
If you only want to convert the number in your loop into a column name (which is what I read from your question) then the following static method is what I use in all of my spreadsheet routines:
You'd need to adjust how you refer to cells slightly. So instead of
You would use
That doesn't really give you any advantages over how you're currently doing it though. The reason I use it is to convert loop counters to column names for reporting purposes, so if you need it for something like that then it probably makes sense.
Here is an excerpt from an ExelTable class, I have been using for a while:
The data is organized in named columns. The name is the first cell in the top row of the data array. The sample code attempts to deal with inperfect name matches and other error situations. One could use more clever collections like
Dictionary<string, int>
to store the mapping between column name and column index.My GetColumn() function allows non-obligatory columns. It is used by GetValue() to return a value in a given row "by name". Questionmarks are returned, if the column was not found.