小记:导出word文档,包含表格以及一个单元格插入多张图片

导出word文档,包含表格以及一个单元格插入多张图片

controller

@ApiOperation(value = "导出安全巡检单")
@GetMapping(path = "/export",produces = {"application/octet-stream;charset=UTF-8"})
public void exportExcel(HttpServletResponse response, String prjName, String prjId) throws IOException, NoSuchFieldException, IllegalAccessException {
    //实体类列表
    List<ConstructionSafety> safeties=constructionSafetyService.getEnd(prjId);
    String fileName="安全巡检档案.doc";
    response.setHeader("content-type", "application/octet-stream");
    response.setContentType("application/octet-stream;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"),"ISO-8859-1"));
    OutputStream outputStream=response.getOutputStream();
    //获取doc文档
    XWPFDocument document =constructionSafetyService.exportDataInfoWord(safeties,prjName);
    document.write(outputStream);
    outputStream.flush();
    outputStream.close();
}

service

//根据实体对象 ,生成XWPFDocument
@Override
public  XWPFDocument exportDataInfoWord(List<ConstructionSafety> list,String prjName) throws NoSuchFieldException,IllegalAccessException {
    //新建doc文档类
    XWPFDocument doc = new XWPFDocument();
    //设置标题。
    XWPFParagraph titleParagraph = doc.createParagraph();
    //设置段落居中
    titleParagraph.setAlignment(ParagraphAlignment.CENTER);
    XWPFRun titleParagraphRun = titleParagraph.createRun();
    titleParagraphRun.setText("安全巡检档案");
    titleParagraphRun.setColor("000000");
    titleParagraphRun.setFontSize(30);
    //设置项目名称
    XWPFParagraph prjParagraph = doc.createParagraph();
    titleParagraph.setAlignment(ParagraphAlignment.CENTER);
    XWPFRun prjParagraphRun = prjParagraph.createRun();
    prjParagraphRun.setText("项目名称:"+prjName);
    prjParagraphRun.setColor("000000");
    prjParagraphRun.setFontSize(15);
    //创建一个列表,12列,因为要导出12个字段的内容,行数是实体列表的个数
    XWPFTable table = doc.createTable(list.size() + 1, 12);
    //表头
    String[] fieldsNames={"序号","巡检单名称","巡检位置","问题类型","问题描述","问题照片","整改要求","检查日期","整改完成时间","整改责任人","整改后照片","复检人"};
    for(int colsIndex=0;colsIndex<fieldsNames.length;colsIndex++){
        //获取第0行第colsIndex列的单元格。
        XWPFTableCell cell = table.getRow(0).getCell(colsIndex);
        //设置内容居中
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        //单元格内段落
        XWPFParagraph p1 = cell.getParagraphs().get(0);
        //段落执行
        XWPFRun r1 = p1.createRun();
        //加粗
        r1.setBold(true);
        r1.setText(fieldsNames[colsIndex]);
    }
    XWPFTableCell cell;
    //列表内容
    for(int rowIndex =1, listIndex =0; listIndex<list.size();rowIndex++,listIndex++){

        cell = table.getRow(rowIndex).getCell(0);
        cell.setText(String.valueOf(rowIndex));

        cell = table.getRow(rowIndex).getCell(1);
        cell.setText(list.get(listIndex).getInspectName());

        cell = table.getRow(rowIndex).getCell(2);
        cell.setText(list.get(listIndex).getInspectLocation());

        cell = table.getRow(rowIndex).getCell(3);
        cell.setText(list.get(listIndex).getProblemType());

        cell = table.getRow(rowIndex).getCell(4);
        cell.setText(list.get(listIndex).getProblemDesc());

        cell = table.getRow(rowIndex).getCell(5);
        //如果没有图片则插入 “暂无图片” 提示字样
        if(!setCellImage(cell,list.get(listIndex).getInspectPhoto())){
            cell.setText("暂无图片");
        }

        cell = table.getRow(rowIndex).getCell(6);
        cell.setText(list.get(listIndex).getRectDesc());

        cell = table.getRow(rowIndex).getCell(7);
        cell.setText(list.get(listIndex).getInspectDate().toString().substring(0,10));

        cell = table.getRow(rowIndex).getCell(8);
        if(list.get(listIndex).getRectSubmitDate()!=null){
            cell.setText(list.get(listIndex).getRectSubmitDate().toString().substring(0,10));
        }

        cell = table.getRow(rowIndex).getCell(9);
        cell.setText(list.get(listIndex).getRectUserFullname());

        cell = table.getRow(rowIndex).getCell(10);
        if(!setCellImage(cell,list.get(listIndex).getAfterPhoto())){
            cell.setText("暂无图片");
        }

        cell = table.getRow(rowIndex).getCell(11);
        cell.setText(list.get(listIndex).getCheckUserFullname());

    }
    return doc;
}

//单元格写入图片
private boolean setCellImage(XWPFTableCell cell, String fileToken) {
    //图片上传group字段判空
    if(StringUtil.isNullOrEmpty(fileToken)){
        return false;
    }
    GetFileInfoParam param=new GetFileInfoParam();
    List<String> g9s=new ArrayList<>();
    g9s.add(fileToken);
    param.setG9s(g9s);
    //查找该group下的所有图片信息
    List<SysOssVO> photos=client.getFileInfoByToken(param).getData();
    //单元格内段落以及段落执行
    List<XWPFParagraph> paragraphs = cell.getParagraphs();
    XWPFParagraph newPara = paragraphs.get(0);
    XWPFRun imageCellRunn = newPara.createRun();
    图片列表判空
    if(photos==null||photos.isEmpty()){
        return false;
    }
    //遍历图片,插入单元格
    for(SysOssVO item:photos){
        String url=item.getFileName();
        int format;
        if (url.endsWith(".emf")) {
            format = XWPFDocument.PICTURE_TYPE_EMF;
        } else if (url.endsWith(".wmf")) {
            format = XWPFDocument.PICTURE_TYPE_WMF;
        } else if (url.endsWith(".pict")) {
            format = XWPFDocument.PICTURE_TYPE_PICT;
        } else if (url.endsWith(".jpeg") || url.endsWith(".jpg")) {
            format = XWPFDocument.PICTURE_TYPE_JPEG;
        } else if (url.endsWith(".png")) {
            format = XWPFDocument.PICTURE_TYPE_PNG;
        } else if (url.endsWith(".dib")) {
            format = XWPFDocument.PICTURE_TYPE_DIB;
        } else if (url.endsWith(".gif")) {
            format = XWPFDocument.PICTURE_TYPE_GIF;
        } else if (url.endsWith(".tiff")) {
            format = XWPFDocument.PICTURE_TYPE_TIFF;
        } else if (url.endsWith(".eps")) {
            format = XWPFDocument.PICTURE_TYPE_EPS;
        } else if (url.endsWith(".bmp")) {
            format = XWPFDocument.PICTURE_TYPE_BMP;
        } else if (url.endsWith(".wpg")) {
            format = XWPFDocument.PICTURE_TYPE_WPG;
        } else {
            ApiResponseBody.error(BizCodeMsgEnum.ERROR);
            continue;
        }
        //根据图片信息去sys-storage服务获取字节数组
        byte[] out=client.downloadPhoto(item.getFileToken()).getData();
        //byte[] 数组判空
        if(out!=null&&out.length>0){
            //byte[] ==> InputStream
            InputStream is=new ByteArrayInputStream(out);
            //is1用来转换成img计算width和height用来等比例缩小图片
            ByteArrayInputStream is1=new ByteArrayInputStream(out);
            BufferedImage img = null;
            try {
                img = javax.imageio.ImageIO.read(is1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int width = img.getWidth();
            int height = img.getHeight();
            //下面按照图片的实际大小进行同比例缩放
            int picHeight = 100;
            int picWidth = picHeight * width/height;
            try {
                //插入图片
                imageCellRunn.addPicture(is, format, url, Units.toEMU(picWidth), Units.toEMU(picHeight));
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return  true;

}

前端

exportSafety() {
      this.$message.warning("正在导出...请耐心等候5-10s")
      Safety.exportSafety(this.prjName, this.prjId).then((data) => {
         if (!data) {
            this.$message.warning("文件下载失败");
            return;
          }
          if (typeof window.navigator.msSaveBlob !== "undefined") {
            window.navigator.msSaveBlob(new Blob([data]), "安全巡检档案.doc");
          } else {
            let url = window.URL.createObjectURL(new Blob([data]));
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", "安全巡检档案.doc");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
      });
    },

注意:不要用poi 3.9及以下版本,同样的代码,poi3.9插入图片后,导出的word文档打不开,报错,改成4.1.0版本后没有问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值