您的位置:首页 > 其它

POI复制行支持07,13。同时复制单元格合并

2017-05-29 14:25 471 查看
在网上找到了一个POI复制行的文章,可惜运行有问题,也不支持07和13。

自己修改了一下,添加了13格式xlsx的支持。使用最新版的poi,去掉过时的字段和方法。

重点是复制行的添加了复制单元格合并。

代码:

/**
* 行复制功能
*
* @param fromRow
* @param toRow
*/
public static void copyRow(Workbook wb, Row fromRow, Row toRow, boolean copyValueFlag) {
toRow.setHeight(fromRow.getHeight());
for(Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext(); ) {
Cell tmpCell = (Cell) cellIt.next();
Cell newCell = toRow.createCell(tmpCell.getColumnIndex());
copyCell(wb, tmpCell, newCell, copyValueFlag);
}
Sheet worksheet = fromRow.getSheet();
for(int i = 0; i < worksheet.getNumMergedRegions(); i++) {
CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
if(cellRangeAddress.getFirstRow() == fromRow.getRowNum()) {
CellRangeAddress newCellRangeAddress = new CellRangeAddress(toRow.getRowNum(), (toRow.getRowNum() +
(cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())), cellRangeAddress
.getFirstColumn(), cellRangeAddress.getLastColumn());
worksheet.addMergedRegionUnsafe(newCellRangeAddress);
}
}
}

/**
* 复制单元格
*
* @param srcCell
* @param distCell
* @param copyValueFlag true则连同cell的内容一起复制
*/
public static void copyCell(Workbook wb, Cell srcCell, Cell distCell, boolean copyValueFlag) {
CellStyle newStyle = wb.createCellStyle();
CellStyle srcStyle = srcCell.getCellStyle();
newStyle.cloneStyleFrom(srcStyle);
newStyle.setFont(wb.getFontAt(srcStyle.getFontIndex()));
//样式
distCell.setCellStyle(newStyle);
//评论
if(srcCell.getCellComment() != null) {
distCell.setCellComment(srcCell.getCellComment());
}
// 不同数据类型处理
CellType srcCellType = srcCell.getCellTypeEnum();
distCell.setCellType(srcCellType);
if(copyValueFlag) {
if(srcCellType == CellType.NUMERIC) {
if(DateUtil.isCellDateFormatted(srcCell)) {
distCell.setCellValue(srcCell.getDateCellValue());
} else {
distCell.setCellValue(srcCell.getNumericCellValue());
}
} else if(srcCellType == CellType.STRING) {
distCell.setCellValue(srcCell.getRichStringCellValue());
} else if(srcCellType == CellType.BLANK) {

} else if(srcCellType == CellType.BOOLEAN) {
distCell.setCellValue(srcCell.getBooleanCellValue());
} else if(srcCellType == CellType.ERROR) {
distCell.setCellErrorValue(srcCell.getErrorCellValue());
} else if(srcCellType == CellType.FORMULA) {
distCell.setCellFormula(srcCell.getCellFormula());
} else {
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poi