简体   繁体   中英

Get Index of Column Name to Map with DataTable C#

I want to import an excel data in database. I have an excel which gets updated by team every month and they add new column with name "Jan data format" (current month name + "data format"). which gets added after the last month column.

DataTable dt = new DataTable();
            dt.Columns.Add("SOURCE");
            dt.Columns.Add("DUMMY CODE");
            dt.Columns.Add("CUSTOMER CODE");
            dt.Columns.Add("STK_CODE");

            DataRow row;

            while (((Microsoft.Office.Interop.Excel.Range)wks.Cells[rowIndex, 1]).Value2 != null)
            {
                row = dt.NewRow();
                row[0] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)wks.Cells[rowIndex, colIndex]).Value2);
                row[1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)wks.Cells[rowIndex, 2]).Value2);
                row[2] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)wks.Cells[rowIndex, 3]).Value2);
                row[3] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)wks.Cells[rowIndex, 4]).Value2);
                index++;

                rowIndex = 2 + index;
                dt.Rows.Add(row);
            }

Here row[1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)wks.Cells[rowIndex, 2]).Value2); i'm using column index. How to use Column Name in place of column index?

The only non-index identifier a column has in Excel is the letter one sees at the top of the column: A , B , etc. This cannot be changed.

Any text typed in a cell above other cells, which looks like a column header/name is just text, as far as Excel is concerned.

I'm using column index. How to use Column Name in place of column index?

So there is no such thing as a "Column Name", therefore there's no way to use string information to identify a column.

It would be necessary to loop all the cells in a row, testing their value, to identify a column that has a particular string as the column heading. Something like

string headerName ="two";
Excel.Worksheet sh = (Excel.Worksheet) excelApp.ActiveSheet;
Excel.Range headerRow = (Excel.Range) sh.UsedRange.Rows[1];
Excel.Range col = null;

foreach(Excel.Range cel in headerRow.Cells)
{
    if (cel.Text.ToString().Equals(headerName))
    {
        col = sh.Range[cel.Address, cel.End[Excel.XlDirection.xlDown]];
        break;
    }
}

foreach(Excel.Range cellInCol in col)
{
    Debug.Print(cellInCol.Value2.ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM