簡體   English   中英

使用 DataTable C# 獲取列名稱的索引到 Map

[英]Get Index of Column Name to Map with DataTable C#

我想在數據庫中導入一個 excel 數據。 我有一個 excel,每個月都會由團隊更新,他們會添加名稱為“Jan 數據格式”(當前月份名稱 +“數據格式”)的新列。 在上個月的列之后添加。

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

這里row[1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)wks.Cells[rowIndex, 2]).Value2); 我正在使用列索引。 如何使用列名代替列索引?

列在 Excel 中唯一的非索引標識符是在列頂部看到的字母: AB等。這是無法更改的。

就 Excel 而言,在其他單元格上方的單元格中鍵入的任何文本(看起來像列標題/名稱)只是文本。

我正在使用列索引。 如何使用列名代替列索引?

所以沒有“列名”這樣的東西,因此無法使用字符串信息來標識列。

有必要循環一行中的所有單元格,測試它們的值,以確定具有特定字符串作為列標題的列。 就像是

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM