C#从intercel获取excel的列名 [英] C# get column name from excel with interop
问题描述
大家好,
这天我正在使用Excel文件。
我需要在其他人之间插入一个列。
我正在使用此代码并且工作正常。
Hi everyone,
I'm working with Excel files on this days.
I need to insert a column beetween some others.
I'm using this code and it's works fine.
Excel.Range araAt = raporWrkS.Range["K1"];
araAt.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight,
Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
在这个代码上我写了K1只是为了样本。并且在if循环中工作。
我从第一列开始,每个新数据都向右移动。但有时我需要在这些列之间插入一个新列。并使用此代码而不是。
但是如何自动编写列名。例如,如果必须在F1上添加新行,则必须为F1。所以我需要从中获取列名。但我不能得到列名。在互联网上查看了很多文档,但它们都有NUMERICAL列名。
你能告诉我一个关于如何获得专栏名称的方法吗?
谢谢。
我尝试了什么:
在网上查找ColumnName属性或类似的东西。
On this code i wrote K1 just for sample. And works in a if loop.
I'm starting from the first column and going to right with every new data. But sometimes i need to insert a new column beetween this columns.And using this code than.
But how can i write column name automatically. For example if new row must to be added on F1 than K1 must be F1. So i need to get column name from that. But i can't get column name. Looked lot of documents on internet but all of them has NUMERICAL column name.
Could you show me a way, about how can i get the column name ?
Thank you.
What I have tried:
Looked the internet for ColumnName property or something like that.
推荐答案
我想知道你为什么要使用这些用户的GUI坐标?
为什么要'你告诉程序直接使用列号吗?
I wonder why you are using those coordinates which is a GUI thing for users ?
Why don't you tell your program to use directly the column number ?
Excel.Range araAt = raporWrkS.cells(columnNumber,1);
araAt.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight,
Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
您可以获取列名从波纹管代码。然后你可以添加新的列名。
You can get column name from the bellow code. Then you can put new column name.
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 = reg.Match(columnName);
columnNames.Add(match.Groups [2] .Value);
}
}
}
)(\w*):"); if (reg.IsMatch(columnName)) { Match match = reg.Match(columnName); columnNames.Add(match.Groups[2].Value); } } }
这篇关于C#从intercel获取excel的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!