Java计算excel中2个单元格的相对位置,根据相对值计算单元格位置

package com.rjxx.util;

public class ExcelColumn {
    /**
     * 根据原位置和偏移量计算目标位置
     * @param src
     * @param row
     * @param col
     * @return
     */
    public static String getLocation(String src,int row,int col) {
        String rows = src.replaceAll("[^a-z^A-Z]", "");
        int rs = excelColStrToNum(rows)+row;
        String cols = src.replaceAll("[^0-9]", "");
        int rs2 = Integer.valueOf(cols)+col;
        return excelColIndexToStr(rs)+rs2;
    }
    
    /**
     * 根据2个单元格位置,计算偏移量
     * @param src
     * @param target
     * @return
     */
    public static int[] getOffset(String src,String target) {
        String row1 = src.replaceAll("[^a-z^A-Z]", "");
        String row2 = target.replaceAll("[^a-z^A-Z]", "");
        int a = excelColStrToNum(row2)-excelColStrToNum(row1);
        String col1 = src.replaceAll("[^0-9]", "");
        String col2 = target.replaceAll("[^0-9]", "");
        int b= Integer.valueOf(col2)-Integer.valueOf(col1);
        int[] ceshi = {a,b};
        return ceshi;
    }
  
    /** 
     * 该方法用来将Excel中的ABCD列转换成具体的数据 
     * @param column:ABCD列名称 
     * @return integer:将字母列名称转换成数字 
     * **/  
    public static int excelColStrToNum(String column) {  
        int num = 0;  
        int result = 0;  
        int length =column.length();   
        for(int i = 0; i < length; i++) {  
            char ch = column.charAt(length - i - 1);  
            num = (int)(ch - 'A' + 1) ;  
            num *= Math.pow(26, i);  
            result += num;  
        }  
        return result;  
    }  
  
    /** 
     * 该方法用来将具体的数据转换成Excel中的ABCD列 
     * @param int:需要转换成字母的数字 
     * @return column:ABCD列名称 
     * **/  
    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;  
    }  
    public static void main(String[] args) {  
        String ZB1 ="AR2";
        String ZB2 ="FE1";
        int[] ceshi = getOffset(ZB1,ZB2);
        System.out.println(ceshi[0]+"---"+ceshi[1]);
        System.out.println(getLocation(ZB1,ceshi[0],ceshi[1]));
    }
}
 

转载于:https://my.oschina.net/sky2008/blog/1845064

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值