All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.hutool.poi.excel.reader.MapSheetReader Maven / Gradle / Ivy

Go to download

Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。

There is a newer version: 5.8.34
Show newest version
package cn.hutool.poi.excel.reader;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 读取{@link Sheet}为Map的List列表形式
 *
 * @author looly
 * @since 5.4.4
 */
public class MapSheetReader extends AbstractSheetReader>> {

	private final int headerRowIndex;

	/**
	 * 构造
	 *
	 * @param headerRowIndex 标题所在行,如果标题行在读取的内容行中间,这行做为数据将忽略
	 * @param startRowIndex 起始行(包含,从0开始计数)
	 * @param endRowIndex   结束行(包含,从0开始计数)
	 */
	public MapSheetReader(int headerRowIndex, int startRowIndex, int endRowIndex) {
		super(startRowIndex, endRowIndex);
		this.headerRowIndex = headerRowIndex;
	}

	@Override
	public List> read(Sheet sheet) {
		// 边界判断
		final int firstRowNum = sheet.getFirstRowNum();
		final int lastRowNum = sheet.getLastRowNum();
		if(lastRowNum < 0){
			return ListUtil.empty();
		}

		if (headerRowIndex < firstRowNum) {
			throw new IndexOutOfBoundsException(StrUtil.format("Header row index {} is lower than first row index {}.", headerRowIndex, firstRowNum));
		} else if (headerRowIndex > lastRowNum) {
			throw new IndexOutOfBoundsException(StrUtil.format("Header row index {} is greater than last row index {}.", headerRowIndex, lastRowNum));
		} else if (startRowIndex > lastRowNum) {
			// issue#I5U1JA 只有标题行的Excel,起始行是1,标题行(最后的行号是0)
			return ListUtil.empty();
		}
		final int startRowIndex = Math.max(this.startRowIndex, firstRowNum);// 读取起始行(包含)
		final int endRowIndex = Math.min(this.endRowIndex, lastRowNum);// 读取结束行(包含)

		// 读取header
		final List headerList = aliasHeader(readRow(sheet, headerRowIndex));

		final List> result = new ArrayList<>(endRowIndex - startRowIndex + 1);
		List rowList;
		for (int i = startRowIndex; i <= endRowIndex; i++) {
			// 跳过标题行
			if (i != headerRowIndex) {
				rowList = readRow(sheet, i);
				if (CollUtil.isNotEmpty(rowList) || false == ignoreEmptyRow) {
					result.add(IterUtil.toMap(headerList, rowList, true));
				}
			}
		}
		return result;
	}
}