问题
I am using Microsoft Interop to read the data.
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?
If you need any other info please let me know.
Regards, Priyank
回答1:
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.
回答2:
You can also Read Column By index
let your Excel work Sheet object is "excelWorksheet" then you can access it as
for setting a value you can use
excelWorksheet.Cells[rowindex, columnindex].Value = "test";
for getting a value you can use
string result = excelWorksheet.Cells[rowindex, columnindex].Value ;
Remember that fields are dynamically generated so 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
excelWorksheet.Cells[1, 2].Value = "test";
I have used it & it works perfectly
来源:https://stackoverflow.com/questions/9721161/microsoft-interop-excel-column-names