1.定位开始位置
2.从开始位置之后,在行索引集合中添加行索引下标
3.截至到结束位置。
4.对行索引集合去重,并循环行索引集合
5.利用XWPFTableRow对像的getCtRow().copy()方法,进行复制(此处复制行单元格,是为了对复制出来的行单元格做其他操作)【如果只是复制,可直接使用table.addRow(newRow, endRowIndex + i);】
6.最后输出doc
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>5.2.5</version>
</dependency>
/**
* @param doc
* @param count 需要循环的次数,最少1次
*/
public static void copyCell(XWPFDocument doc, Integer count) {
if (count < 1) {
return;
}
List<XWPFTable> tables = doc.getTables();
Integer dRowIndex = null;
Integer tableIndex = null;
Boolean isStart = false;
Boolean isEnd = false;
List<Integer> rowIndexs = new LinkedList<>();
for (int i = 0; i < tables.size(); i++) {
XWPFTable table = tables.get(i);
// 遍历表格行
for (int rowIndex = 0; rowIndex < table.getRows().size(); rowIndex++) {
XWPFTableRow row = table.getRow(rowIndex);
// 获取行中的所有单元格
List<XWPFTableCell> cells = row.getTableCells();
// 遍历单元格,获取索引位置
for (int cellIndex = 0; cellIndex < cells.size(); cellIndex++) {
XWPFTableCell cell = cells.get(cellIndex);
String cellText = cell.getText();
if (isStart && !isEnd) {
// 判断单元格是否包含结束标识(此标识是自定义变量)
if (cellText.equalsIgnoreCase("end")) {
isEnd = true;
dRowIndex = rowIndex;
tableIndex = i;
}
rowIndexs.add(rowIndex);
} else {
//判断单元格是否包含开始标识
if (cellText.equalsIgnoreCase("start")) {
isStart = true;
rowIndexs.add(rowIndex);
}
}
}
}
}
if (isStart && isEnd && !rowIndexs.isEmpty()) {
XWPFTable table = tables.get(tableIndex);
List<Integer> uniqueList = rowIndexs.stream().distinct().collect(Collectors.toList());
for (int j = 1; j <= count; j++) {
int endRowIndex = dRowIndex;
for (int i = 1; i <= uniqueList.size(); i++) {
Integer index = uniqueList.get(i - 1);
XWPFTableRow oldRow = table.getRow(index);
//此处复制行单元格,是为了对复制出来的行单元格做编号操作。
XmlObject copy = oldRow.getCtRow().copy();
XWPFTableRow newRow = new XWPFTableRow((CTRow) copy, table);
int finalK = j + 1;
newRow.getTableCells().stream().forEach(cell -> {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(run.getTextPosition());
if (text.contains("【")) {
run.setText(text.substring(0, text.length() - 1).concat(String.valueOf(finalK)).concat("】"), 0);
}
}
}
});
//【如果只是复制,可直接使用table.addRow(newRow, endRowIndex + i);】
table.addRow(newRow, endRowIndex + i);
}
dRowIndex = dRowIndex + uniqueList.size();
}
}
}