java操作word、插入超連結到本地檔案
阿新 • • 發佈:2020-07-11
使用工具:spire.doc.free
一、安裝方法
1.spire.doc.free官網:https://www.e-iceblue.com/,JAVA----Free Spire.Doc for Java----download----Install from Maven Repository
2.配置pom.xml
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories>
<dependencys> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc.free</artifactId> <version>2.7.3</version> </dependency> </dependencys>
二、使用方法
word模板檔案裡面插入書籤----讀取模板檔案----用spire提供的api替換標籤----輸出替換後的檔案
1.普通文字可以直接替換
//載入文件 Document doc = new Document(); doc.loadFromStream(".doc模板檔案路徑"), FileFormat.Docx_2013); //獲取書籤 BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc); bookmarksNavigator.moveToBookmark("title"); bookmarksNavigator.insertText("我是標題");
2.超連結替換
bookmarksNavigator.moveToBookmark("files"); Paragraph paragraph = new Paragraph(doc); // 新增超連結 paragraph.appendHyperlink("連結url", "檔名(要新增連結的文字)", HyperlinkType.Web_Link); // 換行 paragraph.appendBreak(BreakType.Line_Break); // 新增超連結(多個連結一般用for迴圈從list中讀取,新增到paragraph) paragraph.appendHyperlink("連結url", "檔名(要新增連結的文字)", HyperlinkType.Web_Link); TextBodyPart textBodyPart = new TextBodyPart(doc); bookmarksNavigator.replaceBookmarkContent(textBodyPart); textBodyPart.getBodyItems().add(paragraph); bookmarksNavigator.replaceBookmarkContent(textBodyPart);
3.儲存文件
// 儲存到硬碟 doc.saveToFile("檔案路徑", FileFormat.Docx_2013); // 二進位制流的形式返回給前端 response.setContentType("application/binary;charset=UTF-8"); ServletOutputStream out = response.getOutputStream(); doc.saveToStream(out , FileFormat.Docx_2013); out.flush(); out.close(); doc.dispose();