资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

本文实例讲述了Java实现的Excel列号数字与字母互相转换功能。分享给大家供大家参考,具体如下:

创新互联建站专注为客户提供全方位的互联网综合服务,包含不限于网站建设、网站设计、大竹网络推广、成都小程序开发、大竹网络营销、大竹企业策划、大竹品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联建站为所有大学生创业者提供大竹建站搭建服务,24小时服务热线:18982081108,官方网址:www.cdcxhl.com

我们在实现对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程序设计有所帮助。


当前标题:Java实现的Excel列号数字与字母互相转换功能
网页URL:http://cdkjz.cn/article/pgpdgc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220