基于 alibaba/easyexcel
,据称此项目基于 Apache POI 并解决了 OOM 问题。
- 导包
<!-- easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beta4</version>
</dependency>
经测试,发现此项目存在不满足需求之处:不支持在现有模板基础上,传入 list 覆盖表格已有的行,形成新文件
原因在于 com.alibaba.excel.write.ExcelBuilderImpl
中写入 List 数据时,先判断当前表格最后一行,在此行后面续写,保证已有的数据不会覆盖。
- 重新写一个
ExcelEditor
类实现ExcelBuilder
接口
/**
* 可以根据模板修改数据生成新表
* 参考 com.alibaba.excel.write.ExcelBuilderImpl
*/
public class ExcelEditor implements ExcelBuilder {
private WriteContext context;
public ExcelEditor(InputStream inp, OutputStream out, ExcelTypeEnum excelType, boolean needHead) {
try {
POITempFile.createPOIFilesDirectory();
this.context = new WriteContext(inp, out, excelType, needHead);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void addContent(List data, int startRow) {
// 允许覆盖已有行
if (!CollectionUtils.isEmpty(data)) {
for (int i = 0; i < data.size(); ++i) {
int n = i + startRow + 1;
this.addOneRowOfDataToExcel(data.get(i), n);
}
}
}
public void addContent(List data, Sheet sheetParam) {
this.context.currentSheet(sheetParam);
// 覆盖sheet名称
this.context.getWorkbook().setSheetName(sheetParam.getSheetNo() - 1, sheetParam.getSheetName());
this.addContent(data, sheetParam.getStartRow());
}
public void addContent(List data, Sheet sheetParam, Table table) {
this.context.currentSheet(sheetParam);
this.context.currentTable(table);
this.addContent(data, sheetParam.getStartRow());
}
public void merge(int firstRow, int lastRow, int firstCol, int lastCol) {
CellRangeAddress cra = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
this.context.getCurrentSheet().addMergedRegion(cra);
}
/**
* 修改指定cell内容
*
* @param row 行号(起始于0)
* @param col 列号(起始于0)
* @param content 内容(字符串)
*/
public void setCellValue(Integer row, Integer col, String content) {
this.context.getCurrentSheet().getRow(row).getCell(col).setCellValue(content);
}
/**
* 修改指定cell内容
*
* @param row 行号(起始于0)
* @param col 列号(起始于0)
* @param content 内容(日期)
*/
public void setCellValue(Integer row, Integer col, Date content) {
this.context.getCurrentSheet().getRow(row).getCell(col).setCellValue(content);
}
public void finish() {
try {
this.context.getWorkbook().write(this.context.getOutputStream());
this.context.getWorkbook().close();
} catch (IOException e) {
throw new ExcelGenerateException("IO error", e);
}
}
private void addBasicTypeToExcel(List oneRowData, Row row) {
if (!CollectionUtils.isEmpty(oneRowData)) {
for (int i = 0; i < oneRowData.size(); ++i) {
Object cellValue = oneRowData.get(i);
WorkBookUtil.createCell(row, i, this.context.getCurrentContentStyle(), cellValue, TypeUtil.isNum(cellValue));
}
}
}
private void addJavaObjectToExcel(Object oneRowData, Row row) {
int i = 0;
BeanMap beanMap = BeanMap.create(oneRowData);
for (Iterator prop = this.context.getExcelHeadProperty().getColumnPropertyList().iterator(); prop.hasNext(); ++i) {
ExcelColumnProperty excelHeadProperty = (ExcelColumnProperty) prop.next();
String cellValue = TypeUtil.getFieldStringValue(beanMap, excelHeadProperty.getField().getName(), excelHeadProperty.getFormat());
Boolean isNum = TypeUtil.isNum(excelHeadProperty.getField());
// 覆盖已有单元格
Cell cell = row.getCell(i);
if (null == cell) {
cell = row.createCell(i);
}
if (null != cellValue) {
if (isNum) {
cell.setCellValue(Double.parseDouble(cellValue));
} else {
cell.setCellValue(cellValue);
}
}
}
}
private void addOneRowOfDataToExcel(Object oneRowData, int n) {
org.apache.poi.ss.usermodel.Sheet sheet = this.context.getCurrentSheet();
// 覆盖已有行
Row row = sheet.getRow(n);
if (null == row) {
row = sheet.createRow(n);
}
if (oneRowData instanceof List) {
this.addBasicTypeToExcel((List) oneRowData, row);
} else {
this.addJavaObjectToExcel(oneRowData, row);
}
}
}
- 编写 Excel 修改工具类,简化使用
ExcelEditor
/**
* Excel工具类
* 封装com.alibaba.excel
* 封装com.company.ExcelEditor
*/
@Slf4j
public class ExcelUtil {
/**
* 读取指定路径excel到list
*
* @param path 文件路径
* @param sheet sheet参数
*/
public static List readExcel(String path, Sheet sheet) {
try (InputStream inp = new ClassPathResource(path).getInputStream()) {
return EasyExcelFactory.read(inp, sheet);
} catch (Exception e) {
log.warn("解析EXCEL文件异常:", e);
}
return Collections.EMPTY_LIST;
}
/**
* 根据模板修改excel到OutputStream
*
* @param template excel模板路径
* @param out 输出流
* @param excelType excel版本
* @param consumer 处理逻辑
*/
public static void editExcel(String template, OutputStream out, ExcelTypeEnum excelType, Consumer<ExcelEditor> consumer) {
try (InputStream inp = new ClassPathResource(template).getInputStream()) {
ExcelEditor editor = new ExcelEditor(inp, out, excelType, false);
consumer.accept(editor);
editor.finish();
out.flush();
} catch (Exception e) {
log.warn("编辑EXCEL文件异常:", e);
}
}
}
- 测试 excel 修改
// 模板文件地址
String template = "template.xls";
// 模板sheet
Sheet sheet = new Sheet(1, 2, UserModel.class);
sheet.setStartRow(1);
sheet.setSheetName("sheet名称");
// 模板中已有行
List<UserModel> list = (List<UserModel>) ExcelUtil.readExcel(template, sheet);
// 修改list
for (UserModel model : list) {
model.setName("测试")
}
// ServletOutputStream out = response.getOutputStream();
OutputStream out = new FileOutputStream("bbbb.xlsx");
// 输出excel
ExcelUtil.editExcel(template, out, ExcelTypeEnum.XLS, editor -> {
// 用list覆盖数据
editor.addContent(list, sheet);
// 设置指定单元格
editor.setCellValue(1, 2, "测试单元格");
});
经测试:
对于 XLS
格式的模板读写成功。
对于已有数据的行可以覆盖,对于单元格格式不受影响。
如果想让数据出现在更下面的行,可以通过 sheet.setStartRow()
方法指定一个靠下的行号。
网友评论