簡體   English   中英

Microsoft Interop:Excel列名稱

[英]Microsoft Interop: Excel Column Names

我正在使用Microsoft Interop來讀取數據。

在excel-sheet中,列名稱類似於A,B,C,D,....,AA,AB,....等等。 有沒有辦法閱讀這個列名?

如果您需要任何其他信息,請告訴我。

此致,Priyank

     Excel.Application xlApp = new Excel.Application();
     Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("workbookname");
     Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet
     int columnCount = xlWorksheet.UsedRange.Columns.Count;
     List<string> columnNames = new List<string>();
     for (int c = 1; c < columnCount; c++)
     {
         if (xlWorksheet.Cells[1, c].Value2 != null)
         {
             string columnName = xlWorksheet.Columns[c].Address;
             Regex reg = new Regex(@"(\$)(\w*):");
             if (reg.IsMatch(columnName))
             {
                 Match match = reg.Match(columnName);             
                 columnNames.Add(match.Groups[2].Value);
             }                      
        }
     }

這會將每個列名稱放在List<string> ,然后您可以將其綁定到下拉框中。

您還可以按索引讀取列

讓你的Excel工作Sheet對象是“excelWorksheet”然后你可以訪問它

用於設置您可以使用的值

excelWorksheet.Cells [rowindex,columnindex] .Value =“test”;

獲得你可以使用的價值

string result = excelWorksheet.Cells [rowindex,columnindex] .Value;

請記住,字段是動態生成的,因此在編寫代碼時可能會顯示錯誤但忽略它

例如,您要在Excel工作表第1行和第2列中設置文本

excelWorksheet.Cells [1,2] .Value =“test”;

我用過它並且它完美無缺

暫無
暫無

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

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