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

cn.hutool.poi.excel.reader.BeanSheetReader 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.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.poi.excel.cell.CellEditor;
import org.apache.poi.ss.usermodel.Sheet;

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

/**
 * 读取{@link Sheet}为bean的List列表形式
 *
 * @author looly
 * @since 5.4.4
 */
public class BeanSheetReader implements SheetReader> {

	private final Class beanClass;
	private final MapSheetReader mapSheetReader;

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

	@Override
	@SuppressWarnings("unchecked")
	public List read(Sheet sheet) {
		final List> mapList = mapSheetReader.read(sheet);
		if (Map.class.isAssignableFrom(this.beanClass)) {
			return (List) mapList;
		}

		final List beanList = new ArrayList<>(mapList.size());
		final CopyOptions copyOptions = CopyOptions.create().setIgnoreError(true);
		for (Map map : mapList) {
			beanList.add(BeanUtil.toBean(map, this.beanClass, copyOptions));
		}
		return beanList;
	}

	/**
	 * 设置单元格值处理逻辑
* 当Excel中的值并不能满足我们的读取要求时,通过传入一个编辑接口,可以对单元格值自定义,例如对数字和日期类型值转换为字符串等 * * @param cellEditor 单元格值处理接口 */ public void setCellEditor(CellEditor cellEditor) { this.mapSheetReader.setCellEditor(cellEditor); } /** * 设置是否忽略空行 * * @param ignoreEmptyRow 是否忽略空行 */ public void setIgnoreEmptyRow(boolean ignoreEmptyRow) { this.mapSheetReader.setIgnoreEmptyRow(ignoreEmptyRow); } /** * 设置标题行的别名Map * * @param headerAlias 别名Map */ public void setHeaderAlias(Map headerAlias) { this.mapSheetReader.setHeaderAlias(headerAlias); } /** * 增加标题别名 * * @param header 标题 * @param alias 别名 */ public void addHeaderAlias(String header, String alias) { this.mapSheetReader.addHeaderAlias(header, alias); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy