【发布时间】:2021-06-04 01:24:22
【问题描述】:
我知道如何使用 Apache POI 字垂直合并单元格。但是好像新建了一行,合并就不会生效了。
这是输入表:
我希望在old row 2 和old row 3 之间添加一个新行,并将第一列的新行单元格合并到 C2 中,如下所示:
所以我创建了一个新行并将其添加到old row 2下面的表格中,并尝试合并单元格
github源码link is here,可以重现问题。
public class POIWordAddSubRowQuestionDemo{
public static void main(String[] args) throws IOException, XmlException{
ClassLoader classLoader = POIWordAddSubRowQuestionDemo.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("input.docx");
String outputDocxPath = "F:/TEMP/output.docx";
assert inputStream != null;
XWPFDocument doc = new XWPFDocument(inputStream);
XWPFTable table = doc.getTables().get(0);
//this is 'old row 2'
XWPFTableRow secondRow = table.getRows().get(1);
//create a new row that is based on 'old row 2'
CTRow ctrow = CTRow.Factory.parse(secondRow.getCtRow().newInputStream());
XWPFTableRow newRow = new XWPFTableRow(ctrow, table);
XWPFRun xwpfRun = newRow.getCell(1).getParagraphs().get(0).getRuns().get(0);
//set row text
xwpfRun.setText("new row", 0);
// add new row below 'old row 2'
table.addRow(newRow, 2);
//merge cells at first column of 'old row 2', 'new row', and 'old row 3'
mergeCellVertically(doc.getTables().get(0), 0, 1, 3);
FileOutputStream fos = new FileOutputStream(outputDocxPath);
doc.write(fos);
fos.close();
}
static void mergeCellVertically(XWPFTable table, int col, int fromRow, int toRow) {
for(int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
CTVMerge vmerge = CTVMerge.Factory.newInstance();
if(rowIndex == fromRow){
// The first merged cell is set with RESTART merge value
vmerge.setVal(STMerge.RESTART);
} else {
// Cells which join (merge) the first one, are set with CONTINUE
vmerge.setVal(STMerge.CONTINUE);
// and the content should be removed
for (int i = cell.getParagraphs().size(); i > 0; i--) {
cell.removeParagraph(0);
}
cell.addParagraph();
}
// Try getting the TcPr. Not simply setting an new one every time.
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr();
tcPr.setVMerge(vmerge);
}
}
}
但是合并不起作用,我得到了:
另外一次尝试,我尝试根据图3中的表格进行合并,得到图2中的表格,并且成功了。两次尝试之间的唯一区别是 new row 不是新创建的,而是从 docx 文档中读取的,所以我认为创建新行是合并失败的原因。
那么有没有合并新创建的行的解决方案?我真的不想像这样拆分这个操作:添加行>将docx保存到磁盘>从磁盘读取docx>合并行。
【问题讨论】:
-
@AxelRichter 你是对的。为了说明清楚,我写了一个例子上传到了github,链接是github.com/peckwood/stackoverflow-question-code-67830373。这些图像是我用 Paint 绘制的,所以我用实际的 Word 屏幕截图替换了它们。
标签: java ms-word apache-poi row cell