使用 poi 根據 word 模板生成 word 檔案
阿新 • • 發佈:2019-01-28
本例子是一個 maven 專案,要引入 poi 的依賴片段如下:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<!-- 支援Word文件的操作 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.13</version>
</dependency>
注意:要想讓 poi 操作 word ,須要引入 poi-scratchpad
這個模組。
示例程式碼:
@Controller
@RequestMapping("/word")
public class DownLoadController {
@RequestMapping(value = "/download",method = RequestMethod. POST)
public void download(HttpServletRequest request,HttpServletResponse response){
/**
* 獲取請求引數
*/
String pzjg = request.getParameter("pzjg"); // 篇章結構
String gdnr = request.getParameter("gdnr"); // 觀點內容
String jsyy = request.getParameter("jsyy"); // 句式運用
String chyf = request.getParameter("chyf"); // 詞彙語法
String xzgf = request.getParameter("xzgf"); // 寫作規範
// 獲取應用的根路徑
String servletContextRealPath = request.getServletContext().getRealPath("");
// 獲取模板檔案
File templateFile = new File(servletContextRealPath + "/template/template1.doc");
ByteArrayOutputStream ostream = null;
try {
FileInputStream in = new FileInputStream(templateFile);
HWPFDocument hwpfDocument = new HWPFDocument(in);
// 替換讀取到的 word 模板內容的指定欄位
Map<String,String> params = new HashMap<>();
params.put("$PZJG$",pzjg);
params.put("$GDNR$",gdnr);
params.put("$JSYY$",jsyy);
params.put("$CHYF$",chyf);
params.put("$XZGF$",xzgf);
Range range = hwpfDocument.getRange();
for(Map.Entry<String,String> entry:params.entrySet()){
range.replaceText(entry.getKey(),entry.getValue());
}
// 輸出 word 內容檔案流,提供下載
response.reset();
response.setContentType("application/x-msdownload");
// 隨機生成一個檔名
UUID randomUUID = UUID.randomUUID();
String attachmentName = randomUUID.toString();
response.addHeader("Content-Disposition", "attachment; filename=\""+ attachmentName + ".doc\"");
ostream = new ByteArrayOutputStream();
ServletOutputStream servletOS = response.getOutputStream();
hwpfDocument.write(ostream);
servletOS.write(ostream.toByteArray());
servletOS.flush();
servletOS.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
參考資料:
poi 動態呼叫資料