前段时间有个导出word需求,通过Apache POI来开发。POI可以操作MSOffice中常用的三件套Word、Excel、PowerPoint,并且支持2007以上的版本。因为项目针对Word,所以只研究了下POI中XWPF的一些特性,从而达到代码操作生成Word的效果。
引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooml</artifactId>
<version>4.1.1</version>
</dependency>
创建文档代码
XWPFDocument document = new XWPFDocument(); //创建文档
XWPFParagraph paragraph=document.createParagraph(); //创建段落
paragraph.setAlignment(ParagraphAlignment.LEFT); //段落左对齐
XWPFRun run=titleParagraph.createRun(); //创建run
run.setBold(true); //粗体
run.setFontSize(15); //字号
run.setFontFamily("宋体"); //字体
run.setText(""); //输入内容
run.addBreak(); //换行
paragraph.setPageBreak(true);//分页
String path = "xxx.docx";
// 保存文档
FileOutputStream out = new FileOutputStream(path);
document.write(out);
out.close();
document.close();
创建word表格代码
XWPFDocument document = new XWPFDocument(); //创建文档
XWPFTable table = document.createTable(1, 4); //创建表格
table.setWidthType(TableWidthType.AUTO); //自适应行宽
//获取第一行
XWPFTableRow row1 = table.getRow(0);
row1.getCell(0).setWidth(String.valueOf(1500));//第一个单元格行宽
row1.getCell(0).getParagraphArray(0).createRun().setText("");//输入内容
XWPFTableRow row = table.createRow(); //在原来的表格上添加一行
row.getCell(1).getParagraphArray(0).createRun().setText(" "); //每个单元格只有一个段落
row.getCell(1).addParagraph().createRun().setText(" ");//添加段落
//设置表的单元格样式
List<XWPFTableRow> rows = table.getRows();
for(XWPFTableRow row : rows){
List<XWPFTableCell> cells = row.getTableCells();
for(XWPFTableCell cell : cells){
//单元格内容居中
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
List<XWPFParagraph> XWPFParagraphs = cell.getParagraphs();
for(XWPFParagraph paragraph : XWPFParagraphs){
paragraph.setIndentFromLeft(100); //左边距
paragraph.setIndentFromRight(200); //右边距
List<XWPFRun> runs = paragraph.getRuns();
for(XWPFRun tableRun : runs){
tableRun.setFontSize(9);
tableRun.setFontFamily("宋体");
}
}
}
}