1. 添加依賴
確保 Maven 依賴中包含 EasyExcel 3.0.5:
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.0.5</version></dependency><!-- excel工具 --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>
確保代碼與 EasyExcel 3.0.5 及依賴的 POI 版本兼容
2. 自定義樣式處理器
創建?CustomCellStyleHandler
?類實現?CellWriteHandler
?接口,處理標題和內容的樣式:
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Component;import java.util.List;@Component
public class CustomCellStyleHandler implements CellWriteHandler {private CellStyle titleStyle;private CellStyle contentStyle;private void initStyles(Workbook workbook) {if (titleStyle == null) {// 標題樣式titleStyle = workbook.createCellStyle();Font titleFont = workbook.createFont();titleFont.setBold(true); // 加粗titleFont.setFontHeightInPoints((short) 14); // 字體大小titleStyle.setFont(titleFont);titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 背景色}if (contentStyle == null) {// 內容樣式contentStyle = workbook.createCellStyle();Font contentFont = workbook.createFont();contentFont.setFontHeightInPoints((short) 12);contentStyle.setFont(contentFont);contentStyle.setAlignment(HorizontalAlignment.CENTER);contentStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中contentStyle.setBorderTop(BorderStyle.THIN); // 細邊框contentStyle.setBorderBottom(BorderStyle.THIN);contentStyle.setBorderLeft(BorderStyle.THIN);contentStyle.setBorderRight(BorderStyle.THIN);}}@Overridepublic void afterCellDispose(CellWriteHandlerContext context) {// 拿到poi的workbookWorkbook workbook = context.getWriteWorkbookHolder().getWorkbook();initStyles(workbook);// 當前事件會在 數據設置到poi的cell里面才會回調// 判斷不是頭的情況 如果是fill 的情況 這里會==null 所以用not trueif (BooleanUtils.isNotTrue(context.getHead())) {Cell cell = context.getCell();if (cell != null) {cell.setCellStyle(contentStyle);}// 這里要把 WriteCellData的樣式清空, 不然后面還有一個攔截器 FillStyleCellWriteHandler 默認會將 WriteCellStyle 設置到// cell里面去 會導致自己設置的不一樣context.getFirstCellData().setWriteCellStyle(null);}}
}
3. 使用處理器導出數據
在寫入 Excel 時注冊自定義處理器:
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.hieasy.e3.common.excel.CustomCellStyleHandler;import java.util.ArrayList;
import java.util.List;public class ExcelWriter {public static void main(String[] args) {String fileName = "custom_style_example.xlsx";List<DemoData> dataList = new ArrayList<>();dataList.add(new DemoData("Alice", 30));dataList.add(new DemoData("Bob", 28));EasyExcel.write(fileName, DemoData.class).registerWriteHandler(new CustomCellStyleHandler()).sheet("用戶信息").doWrite(dataList);}
}// 數據模型類
class DemoData {@ExcelProperty("姓名")private String name;@ExcelProperty("年齡")private Integer age;public DemoData(String name, Integer age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}
@ApiOperation("一鍵導入")@PostMapping("/import")@ResponseBodypublic R<String> importExcel(@RequestPart MultipartFile file) throws IOException {try {//獲取文件的輸入流InputStream inputStream = file.getInputStream();List<ApiSyncLog> lst = EasyExcel.read(inputStream) //調用read方法.head(ApiSyncLog.class) //對應導入的實體類.sheet(0) //導入數據的sheet頁編號,0代表第一個sheet頁,如果不填,則會導入所有sheet頁的數據.headRowNumber(1) //列表頭行數,1代表列表頭有1行,第二行開始為數據行.doReadSync(); //開始讀Excel,返回一個List<T>集合,繼續后續入庫操作//模擬導入數據庫操作for (ApiSyncLog log1:lst){System.out.println(log1.toString());}}catch (IOException exception){throw new RuntimeException(exception);}return R.ok("Success");}@ApiOperation("一鍵導出")@GetMapping("/export")public void downloadExcel(HttpServletResponse response) throws IOException {// 設置響應頭信息response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");String fileName = URLEncoder.encode("日志文件", "UTF-8");response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");// List<ApiSyncLog> data = new ArrayList<>();// 準備數據List<ApiSyncLog> data = apiSyncLogMapper.selectList(new QueryWrapper<ApiSyncLog>().eq("BillName", "my_jmmd"));// 寫入數據到輸出流EasyExcel.write(response.getOutputStream(), ApiSyncLog.class).registerWriteHandler(new CustomCellStyleHandler()).sheet("Sheet1").doWrite(data);}