Microsoft Interop:Excel列名称
我正在使用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 columnNames = new List (); 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
,然后您可以将其绑定到下拉框中。
您还可以按索引读取列
让你的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”;
我用它并且它完美地工作