poi-3.8.jar、jxls-core-1.0.jar。runRecord.xls,放置於類路徑下(如 RunRecordBSImpl.java 同目錄)。使用 XLSTransformer 將數據模型綁定到模板,生成目標文件。關鍵步驟:
- public class RunRecordBSImpl {
- public void export() {
- String templateFileName = "runRecord.xls";
- String templateFilePath = this.getClass().getResource("").getPath();
- String destFileName = "設備運行記錄卡.xls";
- // 構建數據模型
- Map<String, Object> beans = new HashMap<>();
- Map<String, Object> product = new HashMap<>();
- product.put("model", "XG2016");
- product.put("version", "V1.0");
- beans.put("product", product);
- beans.put("year", "2016");
- beans.put("month", "08");
- beans.put("day", "08");
- Map<String, Object> record = new HashMap<>();
- record.put("inputVoltage", "200");
- record.put("inputVoltageStatus", 0);
- record.put("inputCurrent", "50");
- record.put("inputCurrentStatus", 0);
- beans.put("record", record);
- // 異常列表(需動態合併單元格)
- List<Map<String, Object>> exceptions = new ArrayList<>();
- exceptions.add(Map.of("detail", "輸入電壓過大", "handle", "降低輸入電壓", "handleMode", 1));
- exceptions.add(Map.of("detail", "輸入電流過大", "handle", "降低輸入電流", "handleMode", 1));
- beans.put("exceptions", exceptions);
- // 執行模板轉換
- try (InputStream in = new BufferedInputStream(new FileInputStream(templateFilePath + templateFileName));
- OutputStream out = new FileOutputStream(templateFilePath + destFileName)) {
- XLSTransformer transformer = new XLSTransformer();
- Workbook workbook = transformer.transformXLS(in, beans);
- // 動態合併「異常處理」列單元格
- HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(0);
- int startMergeLine = 7;
- if (!exceptions.isEmpty()) {
- sheet.addMergedRegion(new CellRangeAddress(
- startMergeLine,
- startMergeLine + exceptions.size() - 1,
- 0, 0
- ));
- }
- workbook.write(out);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
${product.model}、jx:forEach 遍歷列表)。直接運行 main 方法,類路徑下將生成 設備運行記錄卡.xls,內容完整對應模板與數據模型。
getClass().getResource("").getPath() 需注意 URL 解碼與路徑分隔符。