最近有需求要动态生成word文档,选用了spire,但spire.doc的免费版只能生成25个table,10page,不能满足需求,后面用了结果有水印,但这个水印发现只会在第一页,嘿嘿。。。那就整他了。。。
二话不说,上代码:
public class DemoOffice {
public static void cleanLicenseFlag(File file) {
try {
XWPFDocument doc = new XWPFDocument(new FileInputStream(file.getPath()));
doc.removeBodyElement(0);
doc.write(new FileOutputStream(file.getPath()));
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File file = new File("D:/test.docx");
Document doc = new Document();
//新增水印页,后续会进行删除
doc.addSection();
//新增内容页,开始写入真实内容
Section section = doc.addSection();
//段落
Paragraph paragraph = section.addParagraph();
paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
TextRange textRange = paragraph.appendText("这是一个word文档");
textRange.getCharacterFormat().setBold(true);
textRange.getCharacterFormat().setFontSize(17f);
doc.saveToFile(file.getPath(), FileFormat.Docx_2013);
doc.close();
cleanLicenseFlag(file);
}
}
前面说了水印只会在第一页,那么原理其实就是一开始新增一页用作专门写水印,然后去掉新增的水印页面。
为什么又引入了apache POI ,因为用spire.doc去操作依然有水印,所以就用了个笨方法换包去,结果还是可以实现的。。。。
下面是pom.xml的依赖
<repositories>
<repository>
<id>iceblue-repository</id>
<name>iceblue</name>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>3.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>
本方法亲测可用的,但要注意spire.doc的版本,版本太高此方法可能不适用的