首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 實現 Excel 模板導出:基於 POI + JXLS 的實戰方案

     編輯:Java 綜合教學

一、準備工作

  1. 下載並引入依賴:poi-3.8.jar、jxls-core-1.0.jar。
  2. 準備 Excel 模板文件 runRecord.xls,放置於類路徑下(如 RunRecordBSImpl.java 同目錄)。

二、核心代碼實現

使用 XLSTransformer 將數據模型綁定到模板,生成目標文件。關鍵步驟:

  1. public class RunRecordBSImpl {
  2. public void export() {
  3. String templateFileName = "runRecord.xls";
  4. String templateFilePath = this.getClass().getResource("").getPath();
  5. String destFileName = "設備運行記錄卡.xls";
  6. // 構建數據模型
  7. Map<String, Object> beans = new HashMap<>();
  8. Map<String, Object> product = new HashMap<>();
  9. product.put("model", "XG2016");
  10. product.put("version", "V1.0");
  11. beans.put("product", product);
  12. beans.put("year", "2016");
  13. beans.put("month", "08");
  14. beans.put("day", "08");
  15. Map<String, Object> record = new HashMap<>();
  16. record.put("inputVoltage", "200");
  17. record.put("inputVoltageStatus", 0);
  18. record.put("inputCurrent", "50");
  19. record.put("inputCurrentStatus", 0);
  20. beans.put("record", record);
  21. // 異常列表(需動態合併單元格)
  22. List<Map<String, Object>> exceptions = new ArrayList<>();
  23. exceptions.add(Map.of("detail", "輸入電壓過大", "handle", "降低輸入電壓", "handleMode", 1));
  24. exceptions.add(Map.of("detail", "輸入電流過大", "handle", "降低輸入電流", "handleMode", 1));
  25. beans.put("exceptions", exceptions);
  26. // 執行模板轉換
  27. try (InputStream in = new BufferedInputStream(new FileInputStream(templateFilePath + templateFileName));
  28. OutputStream out = new FileOutputStream(templateFilePath + destFileName)) {
  29. XLSTransformer transformer = new XLSTransformer();
  30. Workbook workbook = transformer.transformXLS(in, beans);
  31. // 動態合併「異常處理」列單元格
  32. HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(0);
  33. int startMergeLine = 7;
  34. if (!exceptions.isEmpty()) {
  35. sheet.addMergedRegion(new CellRangeAddress(
  36. startMergeLine,
  37. startMergeLine + exceptions.size() - 1,
  38. 0, 0
  39. ));
  40. }
  41. workbook.write(out);
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }

三、模板設計要點

  • 模板中使用 JXLS 語法(如 ${product.model}、jx:forEach 遍歷列表)。
  • 動態行數導致的合併單元格需在生成後通過 POI API 補充(如上代碼)。

四、運行測試

直接運行 main 方法,類路徑下將生成 設備運行記錄卡.xls,內容完整對應模板與數據模型。

五、避坑指南

  • 模板路徑獲取:getClass().getResource("").getPath() 需注意 URL 解碼與路徑分隔符。
  • 大數據量導出建議使用 SXSSF (POI 流式 API) 避免 OOM。
  • JXLS 1.x 較老,新項目推薦 JXLS 2.x + POI 4.x+。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved