I would like to have a function for an XWPFTable that uses Word to dynamically copy rows.
With the word dynamically I mean to copy the value of the cell above and the element number to be able to replace it with the value that I will change later. I am using the Apache POI library
For example, in a row I will have #POR1# in cell x, which will be the percentage of the first element, I want to create a row just after I have #POR2# in cell so that I can then substitute the values
I found a similar function for Excel, but I didn't find it for Word
private static void copyRow(Workbook workbook, Sheet worksheet, int sourceRowNum, int destinationRowNum, int contadorDinamico) {
Row newRow = worksheet.getRow(destinationRowNum);
Row sourceRow = worksheet.getRow(sourceRowNum);
if (newRow != null) {
worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);
}
newRow = worksheet.createRow(destinationRowNum);
for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
Cell oldCell = sourceRow.getCell(i);
Cell newCell = newRow.createCell(i);
if (oldCell == null) {
newCell = null;
continue;
}
// Copy style from old cell and apply to new cell
CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
;
newCell.setCellStyle(newCellStyle);
// If there is a cell comment, copy
if (oldCell.getCellComment() != null) {
newCell.setCellComment(oldCell.getCellComment());
}
// If there is a cell hyperlink, copy
if (oldCell.getHyperlink() != null) {
newCell.setHyperlink(oldCell.getHyperlink());
}
// Set the cell data type
newCell.setCellType(oldCell.getCellType());
if(oldCell.getStringCellValue() != null) {
newCell.setCellValue(oldCell.getStringCellValue().contains("#") ? oldCell.getStringCellValue().substring(0, oldCell.getStringCellValue().length()-2) + contadorDinamico + oldCell.getStringCellValue().substring(oldCell.getStringCellValue().length()-1, oldCell.getStringCellValue().length()) : oldCell.getStringCellValue());
}
}
for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
(newRow.getRowNum() +
(cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow()
)),
cellRangeAddress.getFirstColumn(),
cellRangeAddress.getLastColumn());
worksheet.addMergedRegion(newCellRangeAddress);
}
}
}