本文實例講述了Java實現的Excel列號數字與字母互相轉換功能。分享給大家供大家參考,具體如下:
我們在實現對Excel的導入導出的時候,往往需要準確的給用戶提示信息,提示到具體的Excel的單元格,這裡就需要對Excel的列號進行數字和字母的轉換,今天正好用到這個需求,所以就寫了一個demo,總結一下:
Java實現:
package test;/** * Deal with Excel column indexToStr and strToIndex * @author Stephen.Huang * @version 2015-7-8 */public class ExcelColumn { public static void main(String[] args) { String colstr = "AA"; int colIndex = excelColStrToNum(colstr, colstr.length()); System.out.println("'" + colstr + "' column index of " + colIndex); colIndex = 26; colstr = excelColIndexToStr(colIndex); System.out.println(colIndex + " column in excel of " + colstr); colstr = "AAAA"; colIndex = excelColStrToNum(colstr, colstr.length()); System.out.println("'" + colstr + "' column index of " + colIndex); colIndex = 466948; colstr = excelColIndexToStr(colIndex); System.out.println(colIndex + " column in excel of " + colstr); } /** * Excel column index begin 1 * @param colStr * @param length * @return */ public static int excelColStrToNum(String colStr, int length) { int num = 0; int result = 0; for(int i = 0; i < length; i++) { char ch = colStr.charAt(length - i - 1); num = (int)(ch - 'A' + 1) ; num *= Math.pow(26, i); result += num; } return result; } /** * Excel column index begin 1 * @param columnIndex * @return */ public static String excelColIndexToStr(int columnIndex) { if (columnIndex <= 0) { return null; } String columnStr = ""; columnIndex--; do { if (columnStr.length() > 0) { columnIndex--; } columnStr = ((char) (columnIndex % 26 + (int) 'A')) + columnStr; columnIndex = (int) ((columnIndex - columnIndex % 26) / 26); } while (columnIndex > 0); return columnStr; }}測試結果:
'AA' column index of 2726 column in excel of Z'AAAA' column index of 18279466948 column in excel of ZNSN
更多關於java相關內容感興趣的讀者可查看本站專題:《Java操作Excel技巧總結》、《Java+MySQL數據庫程序設計總結》、《Java數據結構與算法教程》、《Java文件與目錄操作技巧匯總》及《Java操作DOM節點技巧總結》
希望本文所述對大家java程序設計有所幫助。