失独者 2014-06-04 09:27 采纳率: 0%
浏览 4273

使用POI3.10里的在word里插入图片的例子,生成的word打不开报错,如何解决

XWPFDocument doc = new XWPFDocument();//获取文档信息
XWPFParagraph p = doc.createParagraph();
ArrayList list=new ArrayList();
list.add("C:\Users\lu\Desktop\PoiSample\image\1.png");
list.add("C:\Users\lu\Desktop\PoiSample\image\2.png");
XWPFRun r = p.createRun();
for(String imgFile : list) {
int format;
if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
else {
System.err.println("Unsupported picture: " + imgFile +
". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
continue;
}
r.setText(imgFile);
r.addBreak();
r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200));
r.addBreak(BreakType.PAGE);
}
FileOutputStream out = new FileOutputStream("images.docx");
doc.write(out);
out.close();

  • 写回答

1条回答

  • 你知我知皆知 2024-08-02 04:23
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    要解决这个问题,首先确保你的Java环境已经正确安装和配置。然后,请按照以下步骤操作:

    1. 安装Microsoft Office:如果你还没有安装Microsoft Office,则需要从官方网站下载并安装它。

    2. 创建一个新的Word文档:

      WordApp wordApp = new WordApp();
      Document document = wordApp.newDocument();
      
    3. 将图片添加到文档中:

      try {
          // 假设你已经有了一个包含所有图片文件名的列表
          List<String> imagePathList = ...; // 例如:new ArrayList<>(Arrays.asList("C:\\Users\\lu\\Desktop\\PoiSample\\image\\1.png", "C:\\Users\\lu\\Desktop\\PoiSample\\image\\2.png"));
      
          // 创建一段落来放置图片
          Paragraph paragraph = document.createParagraph();
      
          // 遍历图片列表,并创建图片对象
          for (String imagePath : imagePathList) {
              Image image = new Image(imagePath);
              paragraph.addImage(image);
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
      
    4. 保存并关闭文档:

      document.save("output.docx");
      document.close();
      
    5. 如果出现错误,“无法打开或访问指定的文档”,可能是由于缺少必要的字处理库(例如JRE、JDK等)或者缺少相应的依赖库。检查你的开发环境是否已正确配置。

    6. 如果仍然遇到问题,可能是因为图片格式不被Word识别。在这种情况下,可以尝试将图片转换为Word支持的格式(例如PNG),然后再尝试插入。

    评论

报告相同问题?