JAVA生成Word文档

第一步:导入依赖



    com.deepoove
    poi-tl
    1.10.3



    cn.hutool
    hutool-all

第二步:业务代码 

  @Override
    public void downloadEngineeringWord(HttpServletResponse response, Long engineeringId) {
        String engineeringWordSql = "你的查询sql";
        Map tendersWord = (Map) SqlUtil.getMapToList(engineeringWordSql, entityManager).get(0);
        if (ObjectUtils.isEmpty(tendersWord)) {
            return;
        }
        //判断文本是否出现
        if (tendersWord.containsKey("margin") && !ObjectUtils.isEmpty(tendersWord.get("margin"))) {
            BigDecimal price = (BigDecimal) tendersWord.get("margin");
            tendersWord.put("marginShow", price.signum() > 0);
        } else {
            tendersWord.put("marginShow", false);
        }
     
        //将数字金额转为汉字大写
        if (tendersWord.containsKey("maxPrice") && !ObjectUtils.isEmpty(tendersWord.get("maxPrice"))) {
            double money = Double.parseDouble(tendersWord.get("maxPrice").toString());
            String chineseMoney = NumberChineseFormatter.format(money, true, true);
            tendersWord.put("highestPrice", chineseMoney);
        }
        //对前端使用\n换行的段落文本进行格式化换行
        Object qualifications = tendersWord.get("qualifications");
        if (!ObjectUtils.isEmpty(qualifications) && qualifications.toString().contains("/")) {
            List qualificationsList = Arrays.asList(qualifications.toString().split("/"));
            List> qualificationMapList = new ArrayList<>();
            qualificationsList.stream().filter(f -> !ObjectUtils.isEmpty(f.trim())).forEach(qualification -> {
                Map itemMap = new HashMap<>();
                itemMap.put("qualification", qualification);
                qualificationMapList.add(itemMap);
            });
            tendersWord.put("qualifications", qualificationMapList);
        }
       
        String fileName = "工程文件";
        try {
            File wordTemplate = new File("start/src/main/resources/" + fileName + ".docx");
            XWPFTemplate template = XWPFTemplate.compile(wordTemplate.getAbsolutePath()).render(tendersWord);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".docx", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            OutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            template.write(bos);
            bos.flush();
            out.flush();
            PoitlIOUtils.closeQuietlyMulti(template, bos, out);
        } catch (IOException e) {
            throw new BizException(fileName + ".docx 生成失败,请稍后再试!");
        }
    }

官网链接:Poi-tl Documentation 

你可能感兴趣的:(java,word,开发语言)