java 导出自定义Word

Controller代码

@PostMapping(value = "/exportWordDilreport")
    @ApiOperation(httpMethod = "POST", value = "导出演练报告")
    public Wrapper exportWordDilreport(@RequestHeader("token") String token,
                                       @RequestBody DilreportSelDto dilreportDto,
                                       HttpServletRequest request, HttpServletResponse response) throws Exception{

        log.info("------------------- 演练报告下载BEGIN ---------------------------");
        Wrapper wrapper = dilreportService.exportWordDilreport(token,dilreportDto);
        if (wrapper.getCode() == 200) {
            // 上传文件FTP 返回路径
            String title = wrapper.getResult().toString();
            return dilreportService.uploadWordFile(token,wrapper.getMessage(),title);
        }
        log.info("------------------- 演练报告下载END ---------------------------");
        // 删除下载过的文件,不占用资源
        dilreportService.delFiles(token);
        return wrapper;
    }

业务层代码

@Override
    public Wrapper exportWordDilreport(String token, DilreportSelDto dilreportDto) throws Exception{
        // 创建一个文档(
        Document document = new Document(PageSize.A4);//设置纸张大小
        createFile();   // 创建文件夹
        String downUrl = pemBusinessProperties.getWordFile()+"DILRE" + System.currentTimeMillis() + ".doc";      // 服务器需要下载的地址
        //String downUrl = "F:\\word测试\\dilreword\\DILRE" + System.currentTimeMillis() + ".doc";        // 本地需要下载的地址

        // 查询演练报告
        DilreportDto dto = new DilreportDto();
        dto.setTaskId(dilreportDto.getTaskId());
        DilreportVo dilreportVo = new DilreportVo();
        Wrapper wrapper = selectDilreport(token,dto);
        if(null != wrapper) {
            dilreportVo = (DilreportVo) wrapper.getResult();
            if(null != dilreportVo) {
                //try {
                // 查询实操记录
                SelRelationDto selRelationDto = new SelRelationDto();
                selRelationDto.setTaskId(dilreportDto.getTaskId());
                ReportRelationVo reportRelationVo = new ReportRelationVo();
                Wrapper relationWrapper = selectRelationInfo(token,selRelationDto);
                if(null != relationWrapper) {
                    reportRelationVo = (ReportRelationVo) relationWrapper.getResult();
                }

                RtfWriter2.getInstance(document, new FileOutputStream(downUrl));
                //打开word进行填充数据
                document.open();

                Font font10 = FontFactory.getFont("STSong-Light", "Cp1252", 5);         // 通用
                font10.setSize(12);
                font10.setStyle("bold");      // normal  bold  italic oblique  underline line-through
                Font font8 = FontFactory.getFont("STSong-Light", "Cp1252", 5);          // 通用
                font8.setSize(12);

                Paragraph paragraph = new Paragraph(dilreportVo.getReportTitle());
                paragraph.setSpacingBefore(15);
                paragraph.setAlignment(Element.ALIGN_CENTER);      // 居中
                Font font = FontFactory.getFont("STSong-Light", "Cp1252", 5);
                font.setSize(14);
                paragraph.setFont(font);
                document.add(paragraph);

                //创建表格
                Table table = new Table(3);
                table.setWidth(100);
                table.setPadding(5);
                table.setBorder(0);
                table.setBorderColor(Color.WHITE);

                //常见单元格填充图片
                Paragraph paragraph1 = new Paragraph("应急演练", font10);
                paragraph1.setSpacingBefore(10);
                Cell cell1 = getColRowCell(paragraph1);
                table.addCell(cell1, 0, 0);

                Paragraph paragraph2 = getContentSpacingParagraph("演练名称:" + dilreportVo.getDilName(), font8);
                Cell cell2 = getCell(paragraph2);   // 封装通用
                table.addCell(cell2, 3, 0);

                // 将日期格式化
                //String practicalDate = PemDateUtils.getDateAssStrFormat(dilreportVo.getPracticalDate());
                Paragraph paragraph21 = getContentSpacingParagraph("日期:" + dilreportVo.getPracticalDate(), font8);
                Cell cell21 = getCell(paragraph21);   // 封装通用
                table.addCell(cell21, 3, 1);

                Paragraph paragraph22 = getContentSpacingParagraph("起止时间:" + dilreportVo.getStartTime()+"-"+dilreportVo.getEndTime(), font8);
                Cell cell22 = getCell(paragraph22);   // 封装通用
                table.addCell(cell22, 3, 2);

                Paragraph paragraph3 = getContentSpacingParagraph("演练目的:" + dilreportVo.getDilPurposes(), font8);
                Cell cell3 = getCell(paragraph3);   // 封装通用
                table.addCell(cell3, 4, 0);

                Paragraph paragraph31 = getContentSpacingParagraph("演练地点:" + dilreportVo.getPracticalAddress(), font8);
                Cell cell31 = getCell(paragraph31);   // 封装
Paragraph paragraph32 = getContentSpacingParagraph("演练部门/人:" + dilreportVo.getPracticalUserDept(), font8);
                Cell cell32 = getCell(paragraph32);   // 封装通用
                table.addCell(cell32, 4, 2);

                //常见单元格填充图片
                Paragraph paragraph4 = getSpacingMaxParagraph("应急演练方案", font10);
                Cell cell4 = new Cell(paragraph4);
                cell4.setColspan(3);        // 跨列
                cell4.setBorder(0);
                table.addCell(cell4, 5, 0);
                cell4.setHorizontalAlignment(Element.ALIGN_CENTER);

                // 措施以及要求
                Paragraph paragraph6 = getSpacingMaxParagraph(dilreportVo.getProgTitle(), font10);
                paragraph6.setAlignment(Element.ALIGN_CENTER);      // 居中
                Cell cell6 = new Cell(paragraph6);                  // 中间部分整个内容
                cell6.setColspan(3);
                cell6.setBorder(0);

                // 一、演练目的
                Paragraph paragraph61 = getSpacingMaxParagraph("一、演练目的",font10);
                cell6.addElement(paragraph61);
                Paragraph context1 = assemblyParagraph(dilreportVo.getProgPurposes());     // 演练目的内容
                cell6.addElement(context1);

                // 二、组织架构
                Paragraph paragraph62 = getSpacingMaxParagraph("二、组织架构",font10);
                cell6.addElement(paragraph62);
                // 获取组内信息
                if(!CollectionUtils.isEmpty(dilreportVo.getGroupPojoList())){
                    int count = 0;      // ++ 表示 先算结果在输出
                    for(EmergencyGuidanceGroupPojo groupPojo : dilreportVo.getGroupPojoList()){
                        Paragraph groupNamePar = new Paragraph(++count + "、" + groupPojo.getGuidanceGroupName() + ":",font10);         // 救援组/指导组
                        groupNamePar.setIndentationLeft(5);
                        groupNamePar.setIndentationRight(5);
                        cell6.addElement(groupNamePar);
                        Paragraph context2 = new Paragraph( groupPojo.getGuidanceGroupDuty() + groupPojo.getRemark(),font8);         // 演练流程内容
                        context2.setIndentationLeft(15);
                        context2.setIndentationRight(15);
                        cell6.addElement(context2);
                    }
                }

                // 三、演练流程
                Paragraph paragraph63 = getSpacingMaxParagraph("三、演练流程",font10);
                cell6.addElement(paragraph63);
                Paragraph context3 = assemblyParagraph(dilreportVo.getProgProcess());    // 组装富文本
                cell6.addElement(context3);
                table.addCell(cell6, 6, 0);

                // 参加人员
                Paragraph paragraph7 = getSpacingMinParagraph("参加人员签到", font10);
                Cell cell7 = getColRowCell(paragraph7);
                table.addCell(cell7, 7, 0);

                // 参加人员
                Paragraph paragraph8 = getContentParagraph(reportRelationVo.getJoinUser(), font8);
                Cell cell8 = new Cell(paragraph8);
                cell8.setColspan(3);        // 跨列
                cell8.setRowspan(3);        // 跨行
                cell8.setBorder(0);
                table.addCell(cell8, 10, 0);

                // 演练情况记录
                Paragraph paragraph9 = getSpacingMinParagraph("演练情况记录", font10);
                Cell cell9 = getColRowCell(paragraph9);
                table.addCell(cell9, 13, 0);

                // 演练情况记录内容
                Paragraph paragraph10 = assemblyParagraph(reportRelationVo.getContent());
                Cell cell10 = new Cell(paragraph10);
                cell10 = getLeftParagraph("记录人:" + dilreportVo.getNoteUser(), font8, cell10);  // 追加段落
                table.addCell(cell10, 16, 0);

                // 演练总结
                Paragraph paragraph11 = getSpacingMinParagraph("演练总结", font10);
                Cell cell11 = getColRowCell(paragraph11);
                table.addCell(cell11, 19, 0);

                // 演练总结内容
                Paragraph paragraph12 = getContentParagraph(dilreportVo.getProgSummary(), font8);
                Cell cell13 = new Cell(paragraph12);
                cell13 = getLeftParagraph("记录人:" + dilreportVo.getSumingUser(), font8, cell13);  // 追加段落
                table.addCell(cell13, 22, 0);

                // 经理审核意见
                Paragraph paragraph14 = getContentParagraph(dilreportVo.getRevComment(),font8);
                Cell cell14 = new Cell(paragraph14);
                cell14 = getLeftManagerParagraph("经理审核意见:" + dilreportVo.getExamineUser(),font8,cell14);  // 追加段落
                table.addCell(cell14, 25, 0);

                // 将table加入文档中
                document.add(table);

                // 添加图片
                Paragraph paragraph15 = new Paragraph("应急演练照片", font10);
                paragraph15.setSpacingBefore(10);         // 段落下间距
                document.add(paragraph15);

                // 添加照片
                Table table1 = new Table(4);
                table1.setWidth(100);
                table1.setPadding(10);        // 设置列内容间距
                table1.setBorderColor(Color.WHITE);

                // 图片
                if(!CollectionUtils.isEmpty(dilreportVo.getCultivateEncList())){
                    String filename = "";       // 文件名称
                    for(CultivateEnc cultivateEnc : dilreportVo.getCultivateEncList()){
                       if(StringUtils.isNotEmpty(cultivateEnc.getFileUrl())){
                           // 获取文件名
                           filename = cultivateEnc.getFileUrl().substring(cultivateEnc.getFileUrl().lastIndexOf("/")+1);
                           // 获取文件前文件夹
                           String dateDir = cultivateEnc.getFileUrl().replace("//","/");
                           String [] dateDirs = dateDir.split("/");
                           dateDir =  "/" + dateDirs[3] + "/" + dateDirs[4] + "/" + dateDirs[5] + "/";
                           // 下载文件
                           ftpUtil.downloadFtpFile(dateDir,filename);
                        }
                        Image img = Image.getInstance(pemBusinessProperties.getPhotoUrl()+filename);
                        //Image img = Image.getInstance("F:\\word测试\\photo\\"+filename);
                        img.scaleAbsolute(120, 100);         // 设置图片大小
                        Cell cell = new Cell(img);
                        cell.setBorderColor(Color.WHITE);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table1.addCell(cell);
                    }
                }
                document.add(table1);
// 关闭文档
                if (document != null) {
                    document.close();
                }
            }else{
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到演练报告");
            }
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, downUrl,dilreportVo.getReportTitle());
    }


@Override
    public Wrapper uploadWordFile(String token, String fileName,String title) throws Exception {
        // 上传文件至FTP 返回下载路径给前端下载
        File file = new File(fileName);       // 文件路径
        //InputStream inputStream = new FileInputStream(file);
        //String UUID = PubUtils.uuid();            // 生成UUID
        //String remoteFile = new StringBuffer(PemConstants.PEM_UPLODE_SUFFIX).append(UUID).append(FtpFileUtils.getFileType(file.getName())).toString();
        //String remoteFile = new StringBuffer(title).append(System.currentTimeMillis()).append(FtpFileUtils.getFileType(file.getName())).toString();
        //FtpClientTemplate.uploadFile(remoteFile, remoteDirectory, inputStream);        //上传文件
        // 调用文件上传API
        FileInputStream fileInputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        Wrapper<FileUploadVo> fileUploadVoWrapper = fileOperatorFeignApi.uploadFile(PemConstants.BEARER,token,remoteDirectory,multipartFile);
        if(null != fileUploadVoWrapper){
            FileUploadVo uploadVo = fileUploadVoWrapper.getResult();
            if(null != uploadVo){
                return WrapMapper.wrap(Wrapper.SUCCESS_CODE, uploadVo.getFileWebProxyUrl());
            }
        }
        //String fileUrl = FtpFileUtils.getFileUrl(remoteFile, remoteDirectory);
        return WrapMapper.ok();
    }

@Override
    public Wrapper delFiles(String token) throws Exception {
        // 文件地址
        String[] str = {pemBusinessProperties.getWordFile(), pemBusinessProperties.getPhotoUrl()};
        //String[] str = {"F:\\word测试\\dilreword\\", "F:\\word测试\\photo\\"};
        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < str.length; i++) {
            fileList.add(new File(str[i]));
        }
        // 连续创建文件夹以及子集文件夹
        for (File file : fileList) {
            if (file.exists()) {
                File[] files = file.listFiles();       // 所有子集
                for (int i = 0; i < files.length; i++) {
                    if (files[i].exists()) {//删除子文件
                        files[i].delete();
                    }
                }
                file.delete();
            }
        }
        return WrapMapper.ok();
    }

/**
     * 创建文件所需文件夹
     */
    public void createFile() {
        // 文件地址
        String[] str = {pemBusinessProperties.getWordFile(), pemBusinessProperties.getPhotoUrl()};
        //String[] str = {"F:\\word测试\\dilreword\\", "F:\\word测试\\photo\\"};
        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < str.length; i++) {
            fileList.add(new File(str[i]));
        }
        // 连续创建文件夹以及子集文件夹
        for (File file : fileList) {
            if (!file.exists()) {
                file.mkdirs();
            }
        }
    }


    /**
     * 组装富文本读取
     * @param content
     * @return
     * @throws IOException
     */
    public Paragraph assemblyParagraph(String content) throws IOException {
        Paragraph paragraph = new Paragraph();
        paragraph.setIndentationLeft(15);
        //paragraph.setIndentationRight(15);
        StyleSheet styleSheet = new StyleSheet();
        List contList = HTMLWorker.parseToList(new StringReader(content), styleSheet);
        for (int i = 0; i < contList.size(); i++) {
            Element e = (Element) contList.get(i);
            paragraph.add(e);
        }
        return paragraph;
    }

/**
     * 组装段落上下间距
     * @param str
     * @param font
     * @return
     */
    public Paragraph getContentSpacingParagraph(String str,Font font){
        Paragraph paragraph = new Paragraph(str,font);
        //paragraph.setSpacingBefore(2);
        return paragraph;
    }

    /**
     * 组装段落上下间距
     * @param str
     * @param font
     * @return
     */
    public Paragraph getSpacingMaxParagraph(String str,Font font){
        Paragraph paragraph = new Paragraph(str,font);
        paragraph.setSpacingAfter(10);
        paragraph.setSpacingBefore(10);
        return paragraph;
    }

    /**
     * 组装段落上下间距
     * @param str
     * @param font
     * @return
     */
    public Paragraph getSpacingMinParagraph(String str,Font font){
        Paragraph paragraph = new Paragraph(str,font);
        paragraph.setSpacingAfter(6);
        paragraph.setSpacingBefore(6);
        return paragraph;
    }

    /**
     * 组装段落左右间距
     * @param str
     * @param font
     * @return
     */
    public Cell getLeftParagraph(String str,Font font,Cell cell) throws BadElementException{
        Paragraph paragraph = new Paragraph(str,font);
        paragraph.setIndentationLeft(420);
        paragraph.setIndentationRight(15);
        //paragraph.setSpacingAfter(20);
        cell.addElement(paragraph);
        cell.setColspan(3);        // 跨列
        cell.setRowspan(3);        // 跨行
        cell.setBorder(0);
        return cell;
    }

    /**
     * 组装段落左右间距(经理审核意见)
     * @param str
     * @param font
     * @return
     */
    public Cell getLeftManagerParagraph(String str,Font font,Cell cell) throws BadElementException{
        Paragraph paragraph = new Paragraph(str,font);
        paragraph.setIndentationLeft(383);
        paragraph.setIndentationRight(15);
        //paragraph.setSpacingAfter(15);
        cell.addElement(paragraph);
        cell.setColspan(3);        // 跨列
        cell.setRowspan(3);        // 跨行
        cell.setBorder(0);
        return cell;
    }

    /**
     * 组装内容段落
     * @param str
     * @param font
     * @return
     */
    public Paragraph getContentParagraph(String str,Font font){
        Paragraph paragraph = new Paragraph(str,font);
        paragraph.setSpacingAfter(6);
        paragraph.setSpacingBefore(6);
        paragraph.setIndentationLeft(15);
        paragraph.setIndentationRight(15);
        return paragraph;
    }

    /**
     * 组装列(cell)
     * @param paragraph
     * @return
     */
    public Cell getColRowCell(Paragraph paragraph) throws BadElementException{
        Cell cell = new Cell(paragraph);
        cell.setColspan(3);        // 跨列
        cell.setRowspan(3);        // 跨行
        cell.setBorder(0);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        return cell;
    }

    /**
     * 组装列(cell)
     * @param paragraph
     * @return
     */
    public Cell getCell(Paragraph paragraph) throws BadElementException{
        //paragraph.setSpacingAfter(5);
        Cell cell = new Cell(paragraph);
        cell.setBorder(0);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        return cell;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值