springmvc controller层
类在org.apache.poi.xwpf包下
POI在读写word docx文件时是通过xwpf模块来进行的,其核心是XWPFDocument。一个XWPFDocument代表一个docx文档,其可以用来读docx文档,也可以用来写docx文档。XWPFDocument中主要包含下面这几种对象:
XWPFParagraph:代表一个段落。
XWPFRun:代表具有相同属性的一段文本。
XWPFTable:代表一个表格。
XWPFTableRow:表格的一行。
XWPFTableCell:表格对应的一个单元格。
重点介绍写文档,比较灵活,但有点麻烦,也可以通过模板来读之后进行替换。
注意对象的获取与方法的调用
“`
@RequestMapping(value=”/export”,method = {RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public void doWord(HttpServletResponse response){
//创建文档对象
XWPFDocument xdoc = new XWPFDocument();
//设置页眉(自己封装的方法)
simpleDateHeader(xdoc);
//创建段落
XWPFParagraph titleMes1 = xdoc.createParagraph();
//设置段落居中(段落格式利用段落对象调用方法来设置,比如居中,缩进,段落是否站一整页等。)
titleMes1.setAlignment(ParagraphAlignment.CENTER);
//在这个段落之后追加一段相同属性的段落(文本格式通过文本对象调用方法来设置,比如字体颜色,大小等。)
XWPFRun r1 = titleMes1.createRun();
String s1=”hello world”;
r1.setText(s1);
r1.setFontFamily(“微软雅黑”);
r1.addBreak();
int columns = 5;
int rows = 8;//行数
//创建表格对象(一个8行5列的表格)
XWPFTable xTable = xdoc.createTable(rows, columns);
//得到Table的CTTblPr,不存在则新建
CTTbl ttbl = xTable.getCTTbl();
//表格属性
CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
//设置表格宽度
CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
tblWidth.setW(new BigInteger("9600"));
//获取表格第一行(从0开始)
XWPFTableRow row = null;
row = xTable.getRow(0);
//设置行高
row.setHeight(100);
//获取表格的单元格(第一行的第一个,从0开始)
XWPFTableCell cell = null;
cell = row.getCell(0);
//设置内容(也可以使用cell.setParagraph(XWPFParagraph p),单元格里添加一个段落,更易于设置样式)
cell.setText("内容")
ServletOutputStream out = null;
try {
String filename = new String("report.doc".getBytes(),"utf-8");
response.setHeader("Content-Type","application/msword");
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
out = response.getOutputStream();
xdoc.write(out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
out.close();
}
}
//自己写的设置页眉函数
//(通过传文档对象来创建实现,你只需要设置页眉的内容,格式,样式,利用r1对象来设置,可创建多个XWPFRun对象)
public void simpleDateHeader(XWPFDocument document) throws Exception {
CTP ctp = CTP.Factory.newInstance();
XWPFParagraph codePara = new XWPFParagraph(ctp, document);
codePara.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun r1 = codePara.createRun();
r1.setText(“这里是页眉”);
codePara.setBorderBottom(Borders.THICK);
XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
newparagraphs[0] = codePara;
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(
document, sectPr);
headerFooterPolicy.createHeader(STHdrFtr.DEFAULT, newparagraphs);
}
“`