如何在 Java 的 POI 中使用 XWPFTable 合并 2 行或更多行(行跨度)的单元格?
我知道如何将单元格合并成一行,但我不知道该怎么做,而且我没有找到这方面的任何示例。
提前致谢。
最佳答案
找到了!感谢您对 getCTTc().getTcPr()...
和 this site 的评论,这是一个测试垂直合并
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
public class VerticalMerge {
public static void main(String[] args) {
int rows = 5;
int cols = 5;
XWPFDocument document = new XWPFDocument();
XWPFTable table = document.createTable(rows, cols);
fillTable(table);
mergeCellsVertically(table, 3, 1, 3);
try {
FileOutputStream out = new FileOutputStream("vertical merge.docx");
document.write(out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void fillTable(XWPFTable table) {
for (int rowIndex = 0; rowIndex < table.getNumberOfRows(); rowIndex++) {
XWPFTableRow row = table.getRow(rowIndex);
for (int colIndex = 0; colIndex < row.getTableCells().size(); colIndex++) {
XWPFTableCell cell = row.getCell(colIndex);
cell.addParagraph().createRun().setText(" cell " + rowIndex + colIndex + " ");
}
}
}
private static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
if ( rowIndex == fromRow ) {
// The first merged cell is set with RESTART merge value
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
} else {
// Cells which join (merge) the first one, are set with CONTINUE
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
}
}
}
}
目前,它不会连接合并单元格中的文本,但我有一个想法并将很快更新此答案。祝你好运!
关于java - XWPFTable 的行跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24907541/