TOC
POI处理Excel
工具类
@Slf4j
public class PoiUtils {
public static void export(HttpServletResponse response, HttpServletRequest request, Workbook wb, String fileName) throws Exception {
String s = DateUtils.formatDate(new Date(), DateUtils.YYYYMMDD_NO_LINE);
fileName += s;
response.reset();
String name = URLEncoder.encode(fileName + ".xls", "UTF-8");
response.setContentType("application/msexcel");
if (request.getHeader("User-Agent").toLowerCase().contains("firefox")) {
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + name);
} else {
response.setHeader("content-disposition", "attachment; filename=" + name);
}
OutputStream out = response.getOutputStream();
wb.write(out);
out.close();
}
public static void exportLocal(Workbook wb, String url, String name) throws Exception {
url = StringUtils.isBlank(url) ? "c:" : url;
FileOutputStream fileOut = new FileOutputStream(url + "\\\\" + name + ".xls");
wb.write(fileOut);
fileOut.close();
}
public static CellStyle getTitleStyle(Workbook wb) {
Font font = wb.createFont();
font.setFontHeightInPoints((short) 19);
CellStyle style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(font);
return style;
}
public static CellStyle getjzStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
return style;
}
public static CellStyle getBorderStyle(Workbook wb, boolean top, boolean button, boolean left, boolean right, short color, CellStyle style) {
if (top) {
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(color);
}
if (button) {
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(color);
}
if (left) {
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(color);
}
if (right) {
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(color);
}
return style;
}
public static Row setRowStyle(Workbook wb, Row row, int start, int end, CellStyle style) {
Cell cell;
while (start <= end) {
cell = row.createCell(start++);
cell.setCellStyle(style);
}
return row;
}
public static Workbook getWorkbook(String excelName) throws Exception {
InputStream inp = PoiUtils.class.getResourceAsStream("/templates/" + excelName + ".xls");
return WorkbookFactory.create(inp);
}
public static void copyMoreRow(Workbook wb, Sheet sheet, int from, int to, boolean copyValueFlag, int count) {
Row fromRow, toRow;
for (int i = 0; i < count; i++) {
fromRow = sheet.getRow(from + i);
toRow = sheet.createRow(to + i);
PoiUtils.copyRow(wb, sheet, fromRow, toRow, copyValueFlag);
}
}
public static void copyRow(Workbook wb, Sheet sheet, Row fromRow, Row toRow, boolean copyValueFlag) {
toRow.setHeight(fromRow.getHeight());
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
if (cellRangeAddress.getFirstRow() == fromRow.getRowNum()) {
CellRangeAddress newCellRangeAddress = new CellRangeAddress(toRow.getRowNum(), (toRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
sheet.addMergedRegion(newCellRangeAddress);
}
}
for (Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext(); ) {
Cell tmpCell = (Cell) cellIt.next();
Cell newCell = toRow.createCell(tmpCell.getColumnIndex());
copyCell(wb, tmpCell, newCell, copyValueFlag);
}
}
public static void copyCell(Workbook wb, Cell srcCell, Cell distCell, boolean copyValueFlag) {
CellStyle newstyle = wb.createCellStyle();
newstyle.cloneStyleFrom(srcCell.getCellStyle());
distCell.setCellStyle(newstyle);
if (srcCell.getCellComment() != null) {
distCell.setCellComment(srcCell.getCellComment());
}
int srcCellType = srcCell.getCellType();
distCell.setCellType(srcCellType);
if (copyValueFlag) {
if (srcCellType == Cell.CELL_TYPE_NUMERIC) {
if (DateUtil.isCellDateFormatted(srcCell)) {
distCell.setCellValue(srcCell.getDateCellValue());
} else {
distCell.setCellValue(srcCell.getNumericCellValue());
}
} else if (srcCellType == Cell.CELL_TYPE_STRING) {
distCell.setCellValue(srcCell.getRichStringCellValue());
} else if (srcCellType == Cell.CELL_TYPE_BLANK) {
} else if (srcCellType == Cell.CELL_TYPE_BOOLEAN) {
distCell.setCellValue(srcCell.getBooleanCellValue());
} else if (srcCellType == Cell.CELL_TYPE_ERROR) {
distCell.setCellErrorValue(srcCell.getErrorCellValue());
} else if (srcCellType == Cell.CELL_TYPE_FORMULA) {
distCell.setCellFormula(srcCell.getCellFormula());
}
}
}
private static String getValue(Cell cell) {
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue());
}
}
private static String getString(String aa) {
if (StringUtils.isBlank(aa)) {
return "";
} else {
return aa;
}
}
private static String getIntString(Integer aa) {
if (aa == null) {
return "";
} else {
return String.valueOf(aa);
}
}
private static String getDoubleString(Double aa) {
if (aa == null) {
return "";
} else {
return DataUtils.doubleToString(aa);
}
}
public static void copyMoreRowToExcel(Workbook wb, Sheet fromSheet, Sheet toSheet, int from, int to, boolean copyValueFlag, int count) {
Row fromRow, toRow;
for (int i = 0; i < count; i++) {
fromRow = fromSheet.getRow(from + i);
toRow = toSheet.createRow(to + i);
PoiUtils.copyRowToExcel(wb, fromSheet, toSheet, fromRow, toRow, copyValueFlag);
}
fromRow = fromSheet.getRow(1);
for (int i = 0; i < fromRow.getPhysicalNumberOfCells(); i++) {
toSheet.setColumnWidth(i, fromSheet.getColumnWidth(i));
}
}
public static void copyRowToExcel(Workbook wb, Sheet fromSheet, Sheet toSheet, Row fromRow, Row toRow, boolean copyValueFlag) {
toRow.setHeight(fromRow.getHeight());
for (int i = 0; i < fromSheet.getNumMergedRegions(); i++) {
CellRangeAddress cellRangeAddress = fromSheet.getMergedRegion(i);
if (cellRangeAddress.getFirstRow() == fromRow.getRowNum()) {
CellRangeAddress newCellRangeAddress = new CellRangeAddress(toRow.getRowNum(), (toRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
toSheet.addMergedRegion(newCellRangeAddress);
}
}
for (Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext(); ) {
Cell tmpCell = (Cell) cellIt.next();
Cell newCell = toRow.createCell(tmpCell.getColumnIndex());
copyCell(tmpCell, newCell, copyValueFlag);
}
}
public static void copyCell(Cell oldCell, Cell newCell, boolean ifvalue) {
newCell.setCellStyle(oldCell.getCellStyle());
if (ifvalue) {
switch (oldCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BLANK:
newCell.setCellType(Cell.CELL_TYPE_BLANK);
break;
case Cell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
default:
break;
}
}
}
public static void setMergedRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
Row row;
Cell cell;
CellStyle cellStyle = sheet.getRow(firstRow).getCell(firstCol).getCellStyle();
for (int i = firstRow; i <= lastRow; i++) {
row = sheet.getRow(i);
for (int j = firstCol; j <= lastCol; j++) {
if (i == firstRow && j == firstCol) {
continue;
}
cell = row.createCell(j);
cell.setCellStyle(cellStyle);
}
}
sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
}
public static void removeModelSheet(Workbook wb, int id) {
int numberOfSheets = wb.getNumberOfSheets();
for (int i = numberOfSheets - 1; i > -1; i--) {
if (i != id) {
wb.removeSheetAt(i);
}
}
wb.setActiveSheet(0);
}
public static void removeModelSheet(Workbook wb, String name) {
int sheetIndex = wb.getSheetIndex(wb.getSheet(name));
removeModelSheet(wb,sheetIndex);
}
public static void removeModelSheet(Workbook wb, Sheet noDelSheet) {
int sheetIndex = wb.getSheetIndex(noDelSheet);
removeModelSheet(wb,sheetIndex);
}
}
测试
同一个表格内,设置图片
private Workbook startExportWhCg(Entity whCg) throws Exception {
Workbook wb = PoiUtils.getWorkbook("demo");
Sheet sheet = wb.getSheet("页面1");
Drawing patriarch = sheet.createDrawingPatriarch();
PoiUtils.exportWhCg(wb, sheet, patriarch, whCg);
PoiUtils.removeModelSheet(wb, wb.getSheetIndex(sheet));
return wb;
}
public static void exportWhCg(Workbook wb, Sheet sheet, Drawing patriarch, Entity whCg) throws Exception {
Row row = sheet.getRow(start + 1);
row.getCell(2).setCellValue( whCg.getName());
....
int rowIndex = start + 4;
for (Detail weightingDetail : whCg.getPageInfo().getList()) {
Row rowDetail = sheet.getRow(rowIndex++);
int i = 2, j = 0;
rowDetail.getCell(i++).setCellValue(weightingDetail.getName());
....
}
HSSFClientAnchor anchor = new HSSFClientAnchor(400, 5, 0, 254, (short) 2, start + 13, (short) 3, start + 13);
patriarch.createPicture(anchor, wb.addPicture(Base64.decodeBase64(whCg.getStr().substring(17)), HSSFWorkbook.PICTURE_TYPE_JPEG));
}

不同sheet内(实时设置页面)
public void exportQueryGLVoucherData(HttpServletResponse response, HttpServletRequest request, Date date, Integer isNoAccount) throws Exception {
List<AccV> totalList = ...;
String time = DateUtils.formatDate(date, "yyyy年MM月");
String s = time + "账";
Workbook wb = PoiUtils.getWorkbook("demo");
Sheet modelSheet = wb.getSheet("账2");
Sheet sheet = wb.createSheet(s);
final int row = 18;
List<AccV> allList = new ArrayList<>();
for (AccV accVoucherTotal : totalList) {
allList.add(accVoucherTotal);
if (CollectionUtils.isNotEmpty(accVoucherTotal.getList())) {
allList.addAll(accVoucherTotal.getList());
}
accVoucherTotal.setList(null);
}
int totalPage = (int) Math.ceil(allList.size() * 1.0 / row);
for (int i = 0; i < totalPage; i++) {
int start = i * (row + 7);
PoiUtils.copyMoreRowToExcel(wb, modelSheet, sheet, 0, start, true, 4);
for (int j = 0; j < row; j++) {
PoiUtils.copyRowToExcel(wb, modelSheet, sheet, modelSheet.getRow(4), sheet.createRow(start + 4 + j), false);
}
PoiUtils.copyMoreRowToExcel(wb, modelSheet, sheet, 5, start + 4 + row, true, 2);
PoiUtils.setMergedRegion(sheet, start, (start + 4 + row), 4, 4);
String page = "单\r\n据\r\n" + (i + 1) + "/" + totalPage;
int end = Math.min(allList.size(), (i + 1) * row);
PoiUtils.exportQueryGLVoucherData(wb, sheet, allList.subList(i * row, end), time, start, page, DateUtils.formatDate(date, DateUtils.CN_DATE));
}
PoiUtils.removeModelSheet(wb, s);
PoiUtils.export(response, request, wb, s);
}
public static void exportQueryGLVoucherData(Workbook wb, Sheet sheet, List<AccVoucherTotal> subList, String time, int start, String page, String date) {
Row row = sheet.getRow(start);
row.getCell(4).setCellValue(page);
sheet.getRow(start + 1).getCell(0).setCellValue("日期:" + date);
sheet.getRow(start + 1).getCell(2).setCellValue("填制日期:" + DateUtils.formatDate(new Date(), DateUtils.CN_DATE));
if (CollectionUtils.isNotEmpty(subList)) {
int rowIndex = start + 4;
for (AccVoucherTotal oneRow : subList) {
row=sheet.getRow(rowIndex++);
int c=0;
row.getCell(c++).setCellValue(getString(oneRow.getVn())+getString(oneRow.getName()));
row.getCell(c++).setCellValue(getDoubleString(oneRow.getDebitPrice()));
row.getCell(c++).setCellValue(getDoubleString(oneRow.getLendPrice()));
row.getCell(c).setCellValue(getDoubleString(oneRow.getBalance()));
}
}
}

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?