package com.estate.expert.admin.io.processor;
|
|
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.CellType;
|
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
|
import java.util.ArrayList;
|
import java.util.List;
|
|
/**
|
* 行数据处理器基础类
|
*
|
* 用于处理Excel文件的读取和写入
|
*/
|
public abstract class RowDataProcessorBase<T> extends DataProcessorBase<List<T>> {
|
|
protected abstract List<String> buildRowData(T data);
|
|
protected T parseRowData(int rowIndex, List<String> rowData) {
|
return null;
|
}
|
|
@Override
|
protected List<T> parseSheet(XSSFSheet sheet) {
|
var result = new ArrayList<T>();
|
|
int columnCount = getHeaders().length;
|
|
for(int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
|
var row = sheet.getRow(i);
|
// 跳过空行
|
if(row == null) {
|
continue;
|
}
|
var data = new ArrayList<String>();
|
for(int j = 0; j < columnCount; j++) {
|
var cell = row.getCell(j);
|
if(cell == null) {
|
data.add("");
|
} else {
|
data.add(getCellStringValue(cell));
|
}
|
}
|
var rowData = parseRowData(i, data);
|
if(rowData != null) {
|
result.add(rowData);
|
}
|
}
|
return result;
|
}
|
|
@Override
|
protected void writeSheet(XSSFSheet sheet, List<T> data) {
|
var headers = getHeaders();
|
|
int index = 1;
|
for (var d : data) {
|
var rowData = buildRowData(d);
|
if (rowData == null)
|
continue;
|
|
if (rowData.size() != headers.length) {
|
throw new IllegalArgumentException("数据列数与表头列数不一致");
|
}
|
|
var row = sheet.createRow(index++);
|
for (int i = 0; i < rowData.size(); i++) {
|
row.createCell(i).setCellValue(rowData.get(i));
|
}
|
}
|
}
|
|
/**
|
* 获取单元格的字符串值
|
* @param cell 单元格
|
* @return 字符串值
|
*/
|
private String getCellStringValue(Cell cell) {
|
if(cell == null) {
|
return "";
|
}
|
|
CellType cellType = cell.getCellType();
|
if(cellType == CellType.STRING) {
|
return cell.getStringCellValue();
|
} else if(cellType == CellType.NUMERIC) {
|
// 处理数字类型,避免科学计数法
|
double numericValue = cell.getNumericCellValue();
|
// 如果是整数,返回整数格式;否则返回小数格式
|
if(numericValue == (long) numericValue) {
|
return String.valueOf((long) numericValue);
|
} else {
|
return String.valueOf(numericValue);
|
}
|
} else if(cellType == CellType.BOOLEAN) {
|
return String.valueOf(cell.getBooleanCellValue());
|
} else if(cellType == CellType.FORMULA) {
|
// 公式单元格,获取计算后的值
|
try {
|
CellType cachedType = cell.getCachedFormulaResultType();
|
if(cachedType == CellType.STRING) {
|
return cell.getStringCellValue();
|
} else if(cachedType == CellType.NUMERIC) {
|
double numericValue = cell.getNumericCellValue();
|
if(numericValue == (long) numericValue) {
|
return String.valueOf((long) numericValue);
|
} else {
|
return String.valueOf(numericValue);
|
}
|
} else if(cachedType == CellType.BOOLEAN) {
|
return String.valueOf(cell.getBooleanCellValue());
|
} else {
|
return cell.getCellFormula();
|
}
|
} catch (Exception e) {
|
return cell.getCellFormula();
|
}
|
} else if(cellType == CellType.BLANK) {
|
return "";
|
} else {
|
return "";
|
}
|
}
|
|
}
|