【问题标题】:C# Loops with Char and Numbers带有字符和数字的 C# 循环
【发布时间】:2014-02-16 21:29:49
【问题描述】:

我的 C# Winforms 应用程序中有以下代码行:

excell_app.createHeaders(1, 1, "Product_1", "A1", "A1", "n");

"Product_1" 我需要它循环遍历数组中的所有项目,"A1", "A1" 我需要它来获取下一个值,即"B2","B2"

我不确定应该使用哪个循环,因为我需要一个 for next 来遍历我的数组,但是我需要增加 "B2","B2" 的位置值

这是我的尝试:

foreach (string value in ProductName)
{
    excell_app.createHeaders(1, 1, "+ value +", "A1", "A1", "n");
}

我不知道如何通过字母和数字迭代我的位置值:

类似:(我认为这可能是错误的,请指教)

char X='A'+1;
X++

【问题讨论】:

  • 所以“A1”变成“B2”变成“C3”变成“D4”等等? “I9”会发生什么? “J10”?
  • 在Z26 之后应该是AA1,然后是AB2.. 它只是Excel 列。
  • 有一种方法可以在没有字母的情况下访问它们,称为R1C1 reference,这可能会更好。因为 R1 指的是第 1 行,而 C1 指的是第 1 列。迭代可能更容易。不知道如何实现它,所以我不添加答案。我只是不小心将我的工作 xcel 应用程序设置为它并发现了它。
  • 是的,这会有所帮助,但遗憾的是 using Excel = Microsoft.Office.Interop.Excel; 不允许这样做..
  • 您知道字母后面的数字不是列的一部分,而是指定行吗?所以 Z26 表示 Z 列和第 26 行。

标签: c# excel loops do-while


【解决方案1】:

该列基本上是一个以 26 为基数的数字,仅使用字母作为其符号。唯一奇怪的是没有零符号。

这些方法应该可以解决问题:

private static string ExcelCellReference(int col, int row)
{
    return ExcelColumnReference(col) + row;
}

private static string ExcelColumnReference(int col)
{
    if (col <= 0)
    {
        throw new ArgumentOutOfRangeException("col",
            "Value must be greater than or equal to 1.");
    }
    string columnString = "";

    do
    {
        col--;
        int remainder;
        // Math.DivRem divides by 26 and also gets the remainder.
        col = Math.DivRem(col, 26, out remainder);
        columnString = (char)('A' + remainder) + columnString;
    } while (col > 0);

    return columnString;
}

ExcelCellReference(1, 1) 将返回 A1,ExcelCellReference(28, 2) 将返回 AB2,等等。

【讨论】:

  • 太完美了,谢谢
【解决方案2】:
private String getColumnHeader(int column)
{
    column--;
    if (column >= 0 && column < 26)
    {
        return (Char)('A' + column) + "";
    }
    else 
    {
        return getColumnHeader(column / 26) + getColumnHeader(column % 26 + 1);
    }
}

private int getColumnIndex(String reference)
{
    int retVal = 0;
    retVal += reference.Substring(reference.Length - 1)[0] - 'A';
    if (reference.Length > 1)
    {
        reference = reference.Substring(0, reference.Length - 1);
        retVal += 26 * getColumnIndex(reference);
    }

    return retVal + 1;
}

【讨论】:

  • 我想知道你为什么决定使用Uint32。如果您使用无符号类型,则方法签名不符合 CLS,这对于私有方法来说很好,但您似乎不太可能拥有超过 21 亿列?事实上,Excel 目前只支持 16.384。
  • 这些方法属于我创建的一个库,该库是为了使用 OpenXmlSdk 管理 Excel 文件而创建的,所以我只保留 OpenXmlLibrary 中使用的类型,但肯定你是对的!
  • 例如 Uint32Value 它是一个包含只读属性 UInt32 Value 的类;并直接转换为 UInt32
  • 啊,这解释了它......只是作为一个独立的例子令人困惑:)
猜你喜欢
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
相关资源
最近更新 更多