如何在c#中将数值转换为Excel列名,而不使用直接从Excel中获取值的自动化。
Excel 2007的范围可能是1到16384,这是它支持的列数。结果值应以excel列名的形式出现,例如A、AA、AAA等。
如何在c#中将数值转换为Excel列名,而不使用直接从Excel中获取值的自动化。
Excel 2007的范围可能是1到16384,这是它支持的列数。结果值应以excel列名的形式出现,例如A、AA、AAA等。
当前回答
我是这样做的:
private string GetExcelColumnName(int columnNumber)
{
string columnName = "";
while (columnNumber > 0)
{
int modulo = (columnNumber - 1) % 26;
columnName = Convert.ToChar('A' + modulo) + columnName;
columnNumber = (columnNumber - modulo) / 26;
}
return columnName;
}
其他回答
如果你想以实用的方式引用单元格,那么如果你使用工作表的Cells方法,你会得到更可读的代码。它接受行和列索引,而不是传统的单元格引用。它与Offset方法非常相似。
另一个解决方案:
private void Foo()
{
l_ExcelApp = new Excel.ApplicationClass();
l_ExcelApp.ReferenceStyle = Excel.XlReferenceStyle.xlR1C1;
// ... now reference by R[row]C[column], Ex. A1 <==> R1C1, C6 <==> R3C6, ...
}
在这里查看更多- Excel中的单元格引用!作者:Nitin Paranjape博士
private String getColumn(int c) {
String s = "";
do {
s = (char)('A' + (c % 26)) + s;
c /= 26;
} while (c-- > 0);
return s;
}
它不是以26为底,系统中没有0。如果有的话,'Z'后面应该是'BA'而不是'AA'。
下面是一个基于零的列索引的更简单的解决方案
public static string GetColumnIndexNumberToExcelColumn(int columnIndex)
{
int offset = columnIndex % 26;
int multiple = columnIndex / 26;
int initialSeed = 65;//Represents column "A"
if (multiple == 0)
{
return Convert.ToChar(initialSeed + offset).ToString();
}
return $"{Convert.ToChar(initialSeed + multiple - 1)}{Convert.ToChar(initialSeed + offset)}";
}
微软Excel微型,快速和肮脏的公式。
Hi,
下面是一种从数字....获取Excel字符-列-头的方法
我为Excel单元格创建了一个公式。
(即我采取了不使用VBA编程的方法。)
这个公式查看一个有数字的单元格,然后告诉你这个列是什么——用字母表示。
如图所示:
I put 1,2,3 etc in the top row all the way out to column ABS. I pasted my formula in the second row all the way out to ABS. My formula looks at row 1 and converts the number to Excel's column header id. My formula works for all numbers out to 702 (zz). I did it in this manner to prove that the formula works so you can look at the output from the formula and look at the column header above and easily visually verify that the formula works. :-) =CONCATENATE(MID("_abcdefghijklmnopqrstuvwxyz",(IF(MOD(K1,26)>0,INT(K1/26)+1,(INT(K1/26)))),1),MID("abcdefghijklmnopqrstuvwxyz",IF(MOD(K1,26)=0,26,MOD(K1,26)),1))
下划线的存在是为了调试目的——让您知道有一个实际的空格,并且它正在正确地工作。
用上面的公式——不管你在K1里放什么——这个公式会告诉你列的标题是什么。
目前的公式只有2位数字(ZZ),但可以修改为添加第3个字母(ZZZ)。