2014-01-25 20 views
0

我的代码在我的C#的WinForms应用程序下面一行:C#与煤焦循环和数字

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

凡说"Product_1"我就需要遍历我在我的数组中的所有项目,并在那里说"A1", "A1"我需要它来获取下一个值,即"B2","B2"

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

这里是我的尝试:

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

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

是这样的:(我想这可能是错的,请指教)

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

因此, “A1” 变成 “B2” 成为 “C3”,这变成“D4”等? “I9”会发生什么? “J10”? –

+0

在'Z26'之后它应该读取'AA1',然后'AB2' ..它只是Excel列。 – PriceCheaperton

+1

有一种方法可以不用称为[R1C1参考]的字母访问它们(http://www.lytebyte.com/2008/04/29/what-are-a1-and-r1c1-reference-style-in-excel/ )这可能会更好。因为R1指的是第1行,而C1指的是第1列。它可能更容易遍历。不知道如何实现它,所以我没有添加答案。我只是不小心将我的工作xcel应用程序设置为它并发现了它。 –

回答

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)将返回A1ExcelCellReference(28, 2)将返回AB2

1
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; 
} 
+0

我想知道你为什么决定使用'Uint32'。如果您使用无符号类型,方法签名不符合CLS,这对于私有方法来说很好,但是您似乎不太可能拥有超过21亿列?实际上,Excel目前只支持16.384。 – Thorarin

+0

这些方法属于我使用OpenXmlSdk管理Excel文件的库,所以我只保留OpenXmlLibrary中使用的类型,但肯定是您的权利!例如 –

+0

Uint32Value它是一个包含只读属性UInt32 Value的类;并直接投射到UInt32 –