使用Apache POI将Excel / Word转换为PDF

时间:2018-09-25 14:24:21

标签: java excel maven ms-word apache-poi

我正在测试Apache POI,并且有疑问。
我正在使用Maven和Java。

  1. 是否可以在不读取的情况下将excel文件转换为PDF(类似于PdfConverter.getInstance().convert
  2. 如果没有第1步中所述的功能,该如何保留excel样式,格式和其他内容?
  3. 为什么此代码PdfConverter.getInstance().convert(doc,outFile,options);出现以下错误java.lang.ClassNotFoundException:org.apache.poi.POIXMLDocumentPart(请参见下面的代码)?
  4. 还有其他一些我可以免费使用的图书馆吗?

我已经附加了pom.xml和用于单词转换的代码:

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.0</version>
</dependency>

<!-- org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.0</version>
</dependency>   

<!-- org.apache.poi.xwpf.converter.pdf -->
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
    <version>1.0.6</version>
</dependency>    

<!-- com.itextpdf/itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

单词转换代码:

File file1 = new File("myWord.docx");
FileInputStream fileInpStr1 = new FileInputStream(file1.getAbsolutePath());

XWPFDocument doc = new XWPFDocument(fileInpStr1);
OutputStream outFile = new FileOutputStream("myPDFout.pdf"));

PdfOptions options = null;
PdfConverter.getInstance().convert(doc,outFile,options); <-- here the error jumps

outFile.close();
doc.close();

1 个答案:

答案 0 :(得分:1)

尝试通过POI将word(.docx)转换为pdf时遇到了相同的问题。错误为java.lang.NoSuchMethodError:org.apache.poi.POIXMLDocumentPart.getPackageRelationship()Lorg/apache/poi/openxml4j/opc/PackageRelationshipe 我通过将POI的版本从3.16更改为3.15来解决此问题(请参见下面的依赖性)。但我认为这不是最佳解决方案。

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>  <-- right version number
        </dependency>

因此,如果您通过不更改版本来解决此问题,请向我显示您的代码。