欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实现的Excel列号数字与字母互相转换功能

程序员文章站 2022-07-28 15:38:44
本文实例讲述了java实现的excel列号数字与字母互相转换功能。分享给大家供大家参考,具体如下: 我们在实现对excel的导入导出的时候,往往需要准确的给用户提示信息,...

本文实例讲述了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 27
26 column in excel of z
‘aaaa' column index of 18279
466948 column in excel of znsn

更多关于java相关内容感兴趣的读者可查看本站专题:《java操作excel技巧总结》、《java+mysql数据库程序设计总结》、《java数据结构与算法教程》、《java文件与目录操作技巧汇总》及《java操作dom节点技巧总结

希望本文所述对大家java程序设计有所帮助。