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);
OutputStream out = new FileOutputStream("D:\\myTable.docx");
doc.write(out);
}
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;
}
}