Apache POI 4 导出word表格
1. poi依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>4.1.2</version>
</dependency>
2. java代码
package org.bluewing;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.List;
public class ExportWord {
public static void main(String[] args) throws Exception {
ExportWord exportWord = new ExportWord();
XWPFDocument doc = new XWPFDocument();
doc = exportWord.exportTable(doc, 5, 5);
// write the file
OutputStream out = new FileOutputStream("D:\\myTable.docx");
doc.write(out);
}
/**
* 创建表格
*
* @param doc word对象
* @param rows 行数
* @param cols 列数
* @throws Exception
*/
public XWPFDocument exportTable(XWPFDocument doc, int rows, int cols) throws Exception {
XWPFTable table = doc.createTable(rows, cols);
//获取表格所有的行
List<XWPFTableRow> allrows = table.getRows();
//当前选中的行
int currRow = 0;
//当前选中的列
int currCol = 0;
//遍历所有的行,处理表格
for (XWPFTableRow row : allrows) {
//获取当前行的属性对象
CTTrPr rowProperty = row.getCtRow().addNewTrPr();
//获取行高度对象
CTHeight rowheight = rowProperty.addNewTrHeight();
//设置行高度
rowheight.setVal(BigInteger.valueOf(360));
//获取当前行中的所有单元格
List<XWPFTableCell> cells = row.getTableCells();
//遍历单元格,为单元格赋值,设置属性
for (XWPFTableCell cell : cells) {
//获取单元格属性对象
CTTcPr cellProperty = cell.getCTTc().addNewTcPr();
//获取单元格对齐的对象
CTVerticalJc va = cellProperty.addNewVAlign();
//设置居中对齐
va.setVal(STVerticalJc.CENTER);
//获取单元格颜色属性对象
CTShd cellColor = cellProperty.addNewShd();
cellColor.setColor("auto");
cellColor.setVal(STShd.CLEAR);
if (currRow == 0) {
//表头填充色
cellColor.setFill("A7BFDE");
} else if (currRow % 2 == 0) {
//偶数行颜色
cellColor.setFill("D3DFEE");
} else {
// 奇数行颜色
cellColor.setFill("EDF2F8");
}
//创建文本段落
XWPFParagraph para = cell.getParagraphs().get(0);
//创建文本操作对象
XWPFRun run = para.createRun();
if (currRow == 0) {
//表头部分的文字+属性
run.setText("header row, col " + currCol);
run.setFontSize(15);
run.setBold(true);
run.setColor("FFFF00");
para.setAlignment(ParagraphAlignment.CENTER);
} else {
//表格数据部分的文字+属性
run.setText("row: " + currRow + ", col: " + currCol);
run.setFontSize(12);
para.setAlignment(ParagraphAlignment.LEFT);
}
currCol++;
}
//重置当前选中的列
currCol = 0;
currRow++;
}
return doc;
}
}