2014-01-25 25 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 –