com.ludii.excel.parse.DefaultExcelImportCellValueReader Maven / Gradle / Ivy
package com.ludii.excel.parse;
import com.ludii.excel.exceptions.ExcelException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.IOException;
import java.io.InputStream;
/**
* @author 陆迪
* @date 2022/3/24
*/
public class DefaultExcelImportCellValueReader extends AbstractExcelImportCellValueReader {
private final Workbook workbook;
private final Sheet sheet;
private final FormulaEvaluator formulaEvaluator;
private final int dataColumnStartIndex;
public DefaultExcelImportCellValueReader(InputStream inputStream) {
this(inputStream, 0, 0);
}
public DefaultExcelImportCellValueReader(InputStream inputStream, int dataColumnStartIndex) {
this(inputStream, dataColumnStartIndex, 0);
}
public DefaultExcelImportCellValueReader(InputStream inputStream, int dataColumnStartIndex, int sheetIndex) {
try {
this.workbook = WorkbookFactory.create(inputStream);
} catch (EncryptedDocumentException | IOException exception) {
log.error("打开文档报错", exception);
throw new ExcelException(exception);
}
this.dataColumnStartIndex = dataColumnStartIndex;
this.sheet = workbook.getSheetAt(sheetIndex);
if (sheet == null) {
throw new ExcelException(String.format("下标为%s的工作表不存在", sheetIndex));
}
this.formulaEvaluator = this.workbook.getCreationHelper().createFormulaEvaluator();
}
public DefaultExcelImportCellValueReader(InputStream inputStream, int dataColumnStartIndex, String sheetName) {
try {
this.workbook = WorkbookFactory.create(inputStream);
} catch (EncryptedDocumentException | IOException exception) {
log.error("打开文档报错", exception);
throw new ExcelException(exception);
}
this.dataColumnStartIndex = dataColumnStartIndex;
this.sheet = workbook.getSheet(sheetName);
if (sheet == null) {
throw new ExcelException(String.format("%s工作表不存在", sheetName));
}
this.formulaEvaluator = this.workbook.getCreationHelper().createFormulaEvaluator();
}
@Override
protected Sheet getSheet() {
return this.sheet;
}
@Override
protected int getDataRowStartIndex() {
return dataColumnStartIndex;
}
@Override
protected FormulaEvaluator getFormulaEvaluator() {
return formulaEvaluator;
}
@Override
public void close() throws Exception {
if (this.workbook != null) {
this.workbook.close();
}
}
}