1.需求
通過word模板和庫表中數據動態生成word文檔。
word操作工具本身自帶word轉xml(直接另存為xml即可)。
但是需求明確了,只能用word模板,也不允許用戶手動從word轉xml再上傳。
數據動態生成使用了freemark,freemark需要一個xml或flt文件,所以結合上邊的不能傳xml的需求,我將word模板使用Spire.Doc將word模板轉xml,在使用freemark進行xml的動態解析完成了任務
2.問題
在使用Spire.Doc的word文檔產生了警告水印
(Evaluation Warning: The document was created with Spire.Doc for JAVA.)
3.問題解決
3.1. 我是先從網上找方案但是我使用第一種方法直接報錯,也沒找到報錯原因,直接放棄,第二種因為得換包並且有長度限制,直接放棄
方法一:
//重新讀取生成的文檔
InputStream is = new FileInputStream("E:\\demo.docx");
XWPFDocument document = new XWPFDocument(is);
//以上Spire.Doc 生成的文件會自帶警告信息,這里來刪除Spire.Doc 的警告
document.removeBodyElement(0);
//輸出word內容文件流,新輸出路徑位置
OutputStream os=new FileOutputStream("E:\\demo1.docx");
try {
document.write(os);
System.out.println("生成docx文檔成功!");
} catch (Exception e) {
e.printStackTrace();
}
方法二:用free spire.Doc for Java這個是免費版,有一定限制, 導出的時候可生成的段落不能超過固定的數量,但是導出來的Word是沒有警告信息的,商業版的spire.Doc for Java才會有警告信息
————————————————
版權聲明:本文為CSDN博主「一紙的空白」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_33745005/article/details/108140983
3.2. 下面是我的解決方案
我首先想到的是解析每一行的word成數組,然后將第一行元素刪除掉並且將數據輸出到新的文件(我在思考word文檔的格式問題怎么解決,但是我決定先試一下),當我解析出來以后我發現word文檔輸出出來是一行xml。於是我想到了新的解決方式:將xml中的警告直接用空字符串替換掉在輸出,貼代碼
下面方法我是直接對生成的word進行操作的,也可以在word轉xml時直接對xml進行操作,原理和方法完全一樣
//這里是根據解析出的xml抽取出的警告水印的樣式及其xml標簽,方便下面替換用 //如果這里只是替換文字的話會有空行,所以直接將整個標簽替換 private final String WARN = "<w:p><w:pPr /><w:r><w:rPr><w:color w:val=\"FF0000\" /><w:sz w:val=\"24\" /></w:rPr><w:t xml:space=\"preserve\">Evaluation Warning: The document was created with Spire.Doc for JAVA.</w:t></w:r></w:p>"; //原文件 String docName = fileName + uuid + ".doc"; File file = new File(docPath); /** * 消除警告開始 * 創建解析對象,注意這里的包是cn.hutool.core.io.file.FileReader * 因為這里使用jdk自帶的java.io.FileReader時候解析出的xml不全 */ FileReader fileReader = new FileReader(file); String str = fileReader.readString(); //替換 str = str.replaceAll(WARN,""); //輸出,這里的包我就直接用的java.io,用hutool也沒問題 FileWriter fileWriter = new FileWriter(file); fileWriter.write(str);//消除警告結束
下面是word轉xml
//這里的包是com.spire.doc.Document Document doc = new Document(); doc.loadFromStream(inputStream, FileFormat.Doc); doc.saveToFile(xmlPath, FileFormat.Word_Xml); doc.dispose();
使用到的jar包 pom
<repositories> <repository> <id>com.e-iceblue</id> <url>http://repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>3.7.2</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version> </dependency> </dependencies>
4.總結
word的本質其實是xml,這應該也是word存儲樣式的本質。
喜歡記得關注點贊~
轉載請注明出處哦~
https://blog.csdn.net/L_Open2021/article/details/122506478