繁体   English   中英

C#循环使用字符和数字

[英]C# Loops with Char and Numbers

我在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++

该列基本上是基数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)将返回A1ExcelCellReference(28, 2)将返回AB2等。

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM