想在word文档最上边加一个段落怎么办?
可以使用 insertNewParagraph 方法
首先获取XWPFDocument对象
ClassPathResource classPathResource = new ClassPathResource("template/test.docx");
InputStream is = classPathResource.getInputStream();
XWPFDocument doc = new XWPFDocument(is);
然后通过XWPFDocument对象获取段落集合,因为想要插入在最前面,所以获取第一个段落对象
List<XWPFParagraph> paragraphs = doc.getParagraphs();
XWPFParagraph xwpfParagraph = paragraphs.get(0);
再第一个段落前新建一个光标
XmlCursor xmlCursor = xwpfParagraph.getCTP().newCursor();
通过新建的光标对象创建段落,然后根据需要设置段落,就完成插入啦!
XWPFParagraph newParagraph = doc.insertNewParagraph(xmlCursor);
newParagraph.createRun().setText("测试插入");
完整代码如下:
@PostMapping(value = "/printTest")
public void printTest(HttpServletResponse response) {
try {
ClassPathResource classPathResource = new ClassPathResource("template/test.docx");
InputStream is = classPathResource.getInputStream();
XWPFDocument doc = new XWPFDocument(is);
List<XWPFParagraph> paragraphs = doc.getParagraphs();
XWPFParagraph xwpfParagraph = paragraphs.get(0);
XmlCursor xmlCursor = xwpfParagraph.getCTP().newCursor();
XWPFParagraph newParagraph = doc.insertNewParagraph(xmlCursor);
newParagraph.createRun().setText("测试插入");
String name = System.currentTimeMillis() + ".docx";
OutputStream out = response.getOutputStream();
response.reset();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
response.setContentType("application/octet-stream");
response.setHeader("content-Disposition", "form-data;name=\"attachment\";filename=" + name);
doc.write(out);
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
}