2014-04-11 55 views
4

說我的列號是26,當我創建一個公式時,我的公式應該看起來像:例如:SUM(AA1:AA3)。但是如何將26翻譯成AA?或者說27到AB?有沒有辦法讓Apache POI將列索引用作整數並將其轉換爲字母表示形式?Apache poi Excel:根據列的整數索引創建公式

+0

http://stackoverflow.com/questions/2339238/how-to-set-formulas-in-cells-using-apache-poi – Hirak

+0

@Hirak不是問題。問題是使用列號作爲參數而不是使用列字母。 1個與B相關聯,2個與C相關聯,等等。問題是我們開始得到雙重字母。 –

回答

5

這需要一點點代碼:

public static String columnName(int index) { 
    StringBuilder s = new StringBuilder(); 
    while (index >= 26) { 
     s.insert(0, (char) ('A' + index % 26)); 
     index = index/26 - 1; 
    } 
    s.insert(0, (char) ('A' + index)); 
    return s.toString(); 
} 

有所爲測試它:

public static void main(String[] args) { 
    System.out.println(columnName(25)); 
    System.out.println(columnName(26)); 
    System.out.println(columnName(52)); 
    System.out.println(columnName(27 * 26)); 
} 

輸出:

Z 
AA 
BA 
AAA 
1

歐文Bolwidt有正確的想法。

英語這將是:

num/26 - 1 = first_letter 
num % 26  = second_letter 

因此,例如:

27/26 - 1 = 0 => A 
27 % 26  = 1 => B 

這樣:

27 = AB 
+1

Excel 2007及更高版本中的列數限制爲16,384 - 即列名稱XFD [用於索引16,383]。所以你需要3個字母。也許更新的版本允許更多;我的功能可以處理高達Integer.MAX_VALUE - 這將是列FXSHRXX :-) –

+0

哦,我明白了。感謝您的建議。 :) –

7

你要使用CellReference Apache的POI。這提供了你需要轉換

針對您的特殊情況下的方法,你想convertNumToColString(int))

發生在基於0的基數爲10列,並返回一個ALPHA-26表示。

+1

這實際上使Apache POI有內置的很多感覺。 –