poiexcel 读取引用列_Java POI读取Excel的时候怎么按列读取-问答-阿里云开发者社区-阿里云...

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.util.HashMap;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Random;

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

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestPOIP1Title {

public static void main(String[] args) throws Exception {

String pathname = "E:\\files\\title.xlsx";

File file = new File(pathname);

InputStream in = new FileInputStream(file);

//得到整个excel对象

XSSFWorkbook excel = new XSSFWorkbook(in);

//获取整个excel有多少个sheet

int sheets = excel.getNumberOfSheets();

//便利第一个sheet

Map colMap = new HashMap();

for(int i = 0 ; i < sheets ; i++ ){

XSSFSheet sheet = excel.getSheetAt(i);

if(sheet == null){

continue;

}

int mergedRegions = sheet.getNumMergedRegions();

XSSFRow row2 = sheet.getRow(0);

Map category = new HashMap();

for(int j = 0 ; j < mergedRegions; j++ ){

CellRangeAddress rangeAddress = sheet.getMergedRegion(j);

int firstRow = rangeAddress.getFirstColumn();

int lastRow = rangeAddress.getLastColumn();

category.put(rangeAddress.getFirstColumn(), rangeAddress.getLastColumn()+"-"+row2.getCell(firstRow).toString());

}

//便利每一行

for( int rowNum = 1 ; rowNum <= sheet.getLastRowNum() ; rowNum++ ){

System.out.println();

XSSFRow row = sheet.getRow(rowNum);

if(row == null){

continue;

}

short lastCellNum = row.getLastCellNum();

String cate = "";

Integer maxIndex = 0;

for( int col = row.getFirstCellNum() ; col < lastCellNum ; col++ ){

XSSFCell cell = row.getCell(col);

if(cell == null ){

continue;

}

if("".equals(cell.toString())){

continue;

}

int columnIndex = cell.getColumnIndex();

String string = category.get(columnIndex);

if(string != null && !string.equals("")){

String[] split = string.split("-");

cate = split[1];

maxIndex = Integer.parseInt(split[0]);

System.out.println(cate+""+cell.toString());

}else {

//如果当前便利的列编号小于等于合并单元格的结束,说明分类还是上面的分类名称

if(columnIndex<=maxIndex){

System.out.println(cate+""+cell.toString());

}else {

System.out.println("分类未知"+""+cell.toString());

}

}

}

}

}

}

}

运行的结果如下:

bec518c3721e3a333a1a107b376e84c3.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值