pom依赖
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.22</version>
</dependency>
<!--autoPoi-->
<dependency>
<groupId>org.jeecgframework</groupId>
<artifactId>autopoi-web</artifactId>
<version>1.4.6</version>
<exclusions>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency>
<!--easyPoi-->
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-spring-boot-starter -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
工具类如下:
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.sql.Timestamp;
@Slf4j
public class ExcelUtils {
/**
* 合并单元格
*/
public static void mergeRemarks(Workbook workbook, Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
sheet.addMergedRegion(new CellRangeAddress(firstRow, // 第一行(0)
lastRow, // last row(0-based)
firstCol, // 第一列(基于0)
lastCol // 最后一列(基于0)
));
//创建合并但未创建的单元格
createCell(sheet, workbook.getCellStyleAt(24), firstRow, lastRow, firstCol, lastCol);
}
/**
* 根据行列遍历创建单元格
*/
public static void createCell(Sheet sheet, CellStyle cellStyle, int firstRow, int lastRow, int firstCol, int lastCol) {
Row row;
Cell cell;
for (int i = firstRow; i <= lastRow; i++) {
for(int j = firstCol; j <= lastCol; j++) {
row = sheet.getRow(i);
if(row == null) {
row = sheet.createRow(i);
}
if(row.getCell(j) == null) {
cell = row.createCell(j);
cell.setCellStyle(cellStyle);
}
}
}
}
public static CellStyle getCenterCellStyle(Workbook workbook){
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平布局:居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setWrapText(true);
cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
cellStyle.setBorderTop(BorderStyle.THIN);//上边框
cellStyle.setBorderRight(BorderStyle.THIN);//右边框
return cellStyle;
}
/**
* excel文件流输出到浏览器
*/
public static void workBookWrite(String fileName, Workbook workbook, HttpServletResponse response) {
try (OutputStream os = response.getOutputStream()) {
response.