import cn.hutool.core.collection.CollectionUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
@Slf4j
@UtilityClass
public class WriteExcelPOIUtil {
/**
* 读取修改学生数据导入excel单元格内容
*
* @param filePath excel本地路径
* @param fieldMap Map<行, Map<列, 修改内容>>
*/
public void writeStudentExcelPOI(String filePath, Map<Integer, Map<Integer, String>> fieldMap) {
if (CollectionUtil.isEmpty(fieldMap)) {
return;
}
try (XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filePath));) {
XSSFSheet xSheet = workbook.getSheetAt(0); //获取excel表的第一个sheet
//标题在excel中的行数 从0开始
final int TITLE_ROW = 1;
//错误详情在excel的列数 从0开始
final int ERROR_COLUMN = 5;
//标题行添加错误详情字段
modifyTitle(xSheet, TITLE_ROW, ERROR_COLUMN);
//遍历所有需要修改的行
for (Map.Entry<Integer, Map<Integer, String>> rowMap : fieldMap.entrySet()) {
Integer row = rowMap.getKey();
XSSFRow sheetRow = xSheet.getRow(row);
if (sheetRow == null) {
sheetRow = xSheet.createRow(row);
}
//遍历当前行的所有列
for (Map.Entry<Integer, String> columnMap : rowMap.getValue().entrySet()) {
Integer column = columnMap.getKey();
//使用createCell不管这个单元格有没有数据,会直接创建一个空白的单元格覆盖上
XSSFCell xCell = sheetRow.createCell(column);
//修改数据
xCell.setCellValue(columnMap.getValue());
log.debug("第{}行第{}列修改为:{}", row + 1, column + 1, columnMap.getValue());
//设置这行数据背景颜色为黄色
for (int i = 0; i <= column; i++) {
XSSFCell cell = sheetRow.getCell(i);
CellStyle cellStyle = workbook.createCellStyle();
//使用cloneStyleFrom可以保证不会影响其他单元格格式 因为这些单元格使用的是同一个样式
cellStyle.cloneStyleFrom(cell.getCellStyle());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(IndexedColors.YELLOW1.getIndex());
cell.setCellStyle(cellStyle);
}
}
}
//第五列设置列宽自适应
xSheet.autoSizeColumn(ERROR_COLUMN);
try (FileOutputStream out = new FileOutputStream(filePath)) {
workbook.write(out);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void modifyTitle(XSSFSheet xSheet, int TITLE_ROW, int ERROR_COLUMN) {
XSSFRow titleRow = xSheet.getRow(TITLE_ROW);
XSSFCell titleRowCell = titleRow.createCell(ERROR_COLUMN);
CellCopyPolicy cellCopyPolicy = new CellCopyPolicy();
cellCopyPolicy.setCopyCellValue(false);
//复制左边一个单元格格式
titleRowCell.copyCellFrom(titleRow.getCell(ERROR_COLUMN - 1), cellCopyPolicy);
XSSFCellStyle titleRowCellCellStyle = titleRowCell.getCellStyle();
//单元格上方添加黑色的细实线
titleRowCellCellStyle.setBorderTop(BorderStyle.THIN);
titleRowCellCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
titleRowCell.setCellValue("错误详情");
}
}
Java使用POI修改Excel文件
于 2023-02-07 17:51:59 首次发布