C# Microsoft Interop:Excel 列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9721161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:34:00  来源:igfitidea点击:

Microsoft Interop: Excel Column Names

c#office-interopexcel-interop

提问by Priyank Thakkar

I am using Microsoft Interop to read the data.

我正在使用 Microsoft Interop 读取数据。

In excel-sheet the column-names are like A,B,C,D,....,AA,AB,.... and so on. Is there any way to read this column-names?

在 excel-sheet 中,列名就像 A,B,C,D,....,AA,AB,.... 等等。有没有办法读取这个列名?

If you need any other info please let me know.

如果您需要任何其他信息,请告诉我。

Regards, Priyank

问候, 普里扬克

采纳答案by Jetti

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

This will put each column name in a List<string>which you can then bind to a drop down box.

这会将每个列名称放在 a 中List<string>,然后您可以将其绑定到下拉框。

回答by Shivam Srivastava

You can also Read Column By index

您还可以按索引读取列

let your Excel work Sheet object is "excelWorksheet"then you can access it as

让你的 Excel 工作表对象是 “excelWorksheet”然后你可以访问它

for setting a value you can use

用于设置您可以使用的值

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

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

for getting a value you can use

为了获得您可以使用的价值

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

字符串结果 = excelWorksheet.Cells[rowindex, columnindex].Value ;

Remember that fields are dynamically generatedso it may show error in writing your code but ignore that

请记住,字段是动态生成的,因此在编写代码时可能会显示错误,但请忽略它

for example you want to set text in excel sheet row 1 & column 2 then

例如,您想在 Excel 工作表第 1 行和第 2 列中设置文本,然后

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

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

I have used it & it works perfectly

我已经使用过它并且效果很好