对于word文档的生成主要采用的poi生成。 引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
一、第一种方式 主类中编写一种替换方式编写文档
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("${reportContent}", "这是一个难忘的季节");
map.put("${date}", "2021-9-10");
map.put("${author}", "cyz");
map.put("${address}", "中国的一个小城市");
XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage("D:\\word\\template.docx"));
Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
List<XWPFRun> runs = paragraph.getRuns();
for (int i = 0; i < runs.size(); i++) {
String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition()).trim();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (oneparaString.equals(entry.getKey())) {
oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
}
}
runs.get(i).setText(oneparaString, 0);
}
}
FileOutputStream outStream = null;
outStream = new FileOutputStream("D:\\word\\write.docx");
document.write(outStream);
outStream.close();
}
首先我们在template.docx文档中将替换的内容编写好。 其次可以从数据库中获取相应的值,将替换内容当做key,数据库中获取的相应的值当做键值,最后将内容替换后写出到write.docx文档中即可。 二、第二种方式
public static void ExpReprot(HttpServletRequest request,HttpServletResponse response)throws Exception {
response.setContentType("application/msword");
response.setCharacterEncoding("utf-8");
String fileName=URLEncoder.encode("生成报告文档","utf-8").replaceAll("\\+","%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''"+fileName+".doc");
XWPFDocument document=new XWPFDocument();
XWPFParagraph title=document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun=title.createRun();
titleRun.setColor("00000");
titleRun.setFontSize(25);
titleRun.setFontFamily("仿宋");
titleRun.setBold(true);
titleRun.setText("生成报告文档信息");
titleRun.addBreak();
XWPFParagraph firstParagraph=document.createParagraph();
firstParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun firstRun=firstParagraph.createRun();
firstRun.setColor("00000");
firstRun.setFontSize(13);
firstRun.setFontFamily("楷体");
firstRun.setBold(true);
firstRun.setText("这是一份有关于经济方面的报告,如何增长,如何促进本市的经济发展,促进消费,拉动经济。");
firstRun.addBreak();
firstRun.addTab();
firstRun.setText("虽然目前经济来说,由于疫情的影响,消费拉动经济确实有点困难,但线上的消费同样也可以促进经济发展,所以应该大力发展。");
firstRun.addBreak();
XWPFParagraph secondParagraph=document.createParagraph();
secondParagraph.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun secondRun=firstParagraph.createRun();
secondRun.setText("这是第二段落");
document.write(response.getOutputStream());
document.close();
}
|