导入easy-poi相关依赖
<!-- word导出 方式:easypoi --><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.4.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-web</artifactId><version>4.4.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-annotation</artifactId><version>4.4.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.1</version></dependency>
文档模版
控制层业务层相关代码
/*** 导出*/@GetMapping("/exportVehiclePurchaseOrder")public void exportVehiclePurchaseOrder(HttpServletResponse response) {// 创建Word文档并填充数据vehiclePurchaseOrderService.exportVehiclePurchaseOrder(response);}
try {// 相关数据信息由于业务原因就不展示了,相关数据在使用时候可以自己创建Map<String, Object> datas = new HashMap<String, Object>();Date createdTime = vehiclePurchaseOrder.getCreatedTime();datas.put("title", "车辆采购订单");datas.put("time", DateUtil.format(createdTime, "yyyy-MM-dd HH:mm:ss"));datas.put("procurementNo", vehiclePurchaseOrder.getPurchaseNo());datas.put("companyName", company.getName());String brand = DictDataUtils.getDictNameByCode("company_brand", company.getBrand());datas.put("brand", brand);datas.put("num", list.size());// 列表数据if (CollUtil.isNotEmpty(list)) {List<Map<String, Object>> data = new ArrayList<>();int num = 1;for (Vehicle vehicle : list) {Map<String, Object> row = new HashMap<>();row.put("no", String.valueOf(num));String vehicleBrand = DictDataUtils.getDictNameByCode("vehicle_brand", vehicle.getBrand());String vehicleModel = DictDataUtils.getDictNameByCode("vehicle_model", vehicle.getModelNo());row.put("vehicleBrand", vehicleBrand);row.put("vehicleModel", vehicleModel);row.put("licensePlateNo", vehicle.getLicensePlateNo());num++;data.add(row);}datas.put("list", data);}// 模版存放路径--服务器String path = "/evmmp_manage_data/template.docx";// String path = URLDecoder.decode(this.getClass().getClassLoader().getResource("templates/template.docx").getPath(), "UTF-8");FileUtils.exportWordByModel(response, datas, path, vehiclePurchaseOrder.getPurchaseNo() + "_" + System.currentTimeMillis());} catch (Exception e) {throw new ServiceException("导出采购订单失败");}
public class FileUtils {/*** 根据模板导出Word** @param response* @param map* @param modelFileName* @param outFileName*/public static void exportWordByModel(HttpServletResponse response, Map<String, Object> map, String modelFileName, String outFileName) {try {// 映射模板,替换数据XWPFDocument word = WordExportUtil.exportWord07(modelFileName, map);response.reset();response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment;filename=" + outFileName + ".docx");// 将Word文档发送到浏览器word.write(response.getOutputStream());word.close();} catch (Exception e) {e.printStackTrace();}}
测试: