在 C# 中循环字母表以输出到 Excel 的最佳方法是什么?
我有导出到 Excel 的代码,并且有一个列数组。 。
var colheaders = new string[] {"Name", "Age", "Total", "Date"}
现在我有看起来像这样的代码来设置标题,
excelExport.SetCell("A", 1, "Name");
excelExport.SetCell("B", 1, "Age");
excelExport.SetCell("C", 1, "Total");
excelExport.SetCell("D", 1, "Date");
问题是如果我有 50 列并且我想在开头添加一列,我必须去更新每一列“A”、“B”中的字母、“C”等。 。
因为我已经有一个字符串标题数组,所以我想要这样的东西:
foreach (string colheader in colheaders)
{
excelExport.SetCell("A", 1, colheader);
}
但在这种情况下我需要动态设置字母“A”。像这样的东西:
int i = 0;
foreach (string colheader in colheaders)
{
excelExport.SetCell(GetCol(i), 1, colheader);
i++;
}
注意:
另外,在Z之后,我需要去AA,然后AB,然后AC,等等。 。为了匹配 Excel 列,因此逻辑必须超过 26 列
I have code that is exporting to excel and i have an array of columns . .
var colheaders = new string[] {"Name", "Age", "Total", "Date"}
right now i have code that looks like this to setup the headers
excelExport.SetCell("A", 1, "Name");
excelExport.SetCell("B", 1, "Age");
excelExport.SetCell("C", 1, "Total");
excelExport.SetCell("D", 1, "Date");
the issue is that if i have 50 columns and i want to add one at the beginnging, i have to go and updated the letter in each column "A", "B", "C", etc . .
since i have an array already of string headers i would like something like this:
foreach (string colheader in colheaders)
{
excelExport.SetCell("A", 1, colheader);
}
but i need to dynamically set the letter "A" in this case. Something like this:
int i = 0;
foreach (string colheader in colheaders)
{
excelExport.SetCell(GetCol(i), 1, colheader);
i++;
}
NOTE:
Also, after Z, i need to go to AA, then AB, then AC, etc . . to match the Excel columns so the logic would have to go beyond 26 columns
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是最优雅的解决方案,但它确实产生了您正在寻找的结果。
This isn't the most elegant solution but it does yield the result you are looking for.
我在 stackoverflow 上找到了另一个有可行解决方案的问题:
这是问题: 在 C# 中生成 Excel 列字母的最快函数
,答案是:ExcelColumnFromNumber() 方法
I was able to find another question on stackoverflow that had a working solution:
Here is the question: Fastest function to generate Excel column letters in C#
and the answer is the: ExcelColumnFromNumber() method
根据
SetCell
的定义,您也许可以这样做:例如,如果 SetCell 定义如下:
Depending on the definition of
SetCell
, you may be able to do this:This would work, for example, if SetCell were defined thus: