ITeye博客

把行号(row)和列号(col)转换成Excel的表示形式。 例如:A1,B2

Goro · 2012-09-24 20:51 · Java · 编程语言 · Markdown

0,0 ⇒ A1


import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;

public class TestPOI {
	public static void main(String[] args) {
		System.out.println(getCellName(0, 0)); //A1
		System.out.println(getCellName(3, 28)); //AC4
		System.out.println(getCellName(5, 255)); //IV6
		
	}
	
	public static String getCellName(int row, int col) {
		if (row < 0) {
			throw new IllegalArgumentException("row: " + row);
		}
		if (col < 0) {
			throw new IllegalArgumentException("col: " + col);
		}		
		//return CellReference.convertNumToColString(col) + (row + 1);
		return new CellReference(row, col).formatAsString();
	}
}

输出: A1 AC4 IV6

需要区域转换成


CellRangeAddress address = new CellRangeAddress(0, 4, 0, 3);
System.out.println(address.formatAsString());

输出: A1:D5

其中用了POI的库,下载。 http://poi.apache.org/download.html

如果希望反过来。 A1 ⇒ 0,0


CellReference cr = new CellReference("A1");
System.out.println(cr.getRow() + ":" + cr.getCol());

区域的


CellRangeAddress address = CellRangeAddress.valueOf("A1:D5");
int firstRow = address.getFirstRow();
int lastRow = address.getLastRow();
int firstColumn = address.getFirstColumn();
int lastColumn = address.getLastColumn();
System.out.println(firstRow + ":" + lastRow + ":" + firstColumn + ":" + lastColumn);

输出: 0:4:0:3

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。