public static HSSFWorkbook appendWorkBook(Workbook targetWorkBook, Workbook sourceWorkbook) {
for (int j = 0; j < sourceWorkbook.getNumberOfSheets(); j++) {
Sheet oldSheet = sourceWorkbook.getSheetAt(j);
Sheet newSheet = targetWorkBook.createSheet(oldSheet.getSheetName());
mergeSheetAllRegion(oldSheet, newSheet);
// 设置列宽
int length = oldSheet.getRow(oldSheet.getFirstRowNum()).getLastCellNum();
for (int i = 0; i <= length; i++) {
newSheet.setColumnWidth(i, oldSheet.getColumnWidth(i));
}
CellStyle newstyle = targetWorkBook.createCellStyle();
for (Iterator rowIt = oldSheet.rowIterator(); rowIt.hasNext(); ) {
Row oldRow = (Row) rowIt.next();
Row newRow = newSheet.createRow(oldRow.getRowNum());
newRow.setHeight(oldRow.getHeight());
for (Iterator cellIt = oldRow.cellIterator(); cellIt.hasNext(); ) {
Cell tmpCell = (Cell) cellIt.next();
Cell newCell = newRow.createCell(tmpCell.getColumnIndex());
// 复制单元格样式
newstyle.cloneStyleFrom(tmpCell.getCellStyle());
// 样式
newCell.setCellStyle(newstyle);
if (tmpCell.getCellComment() != null) {
newCell.setCellComment(tmpCell.getCellComment());
}
// 不同数据类型处理
CellType fromCellType = tmpCell.getCellType();
newCell.setCellType(fromCellType);
if (fromCellType == CellType.NUMERIC) {
if (DateUtil.isCellDateFormatted(tmpCell)) {
newCell.setCellValue(tmpCell.getDateCellValue());
} else {
newCell.setCellValue(tmpCell.getNumericCellValue());
}
} else if (fromCellType == CellType.STRING) {
newCell.setCellValue(tmpCell.getRichStringCellValue());
} else if (fromCellType == CellType.BLANK) {
// nothing21
} else if (fromCellType == CellType.BOOLEAN) {
newCell.setCellValue(tmpCell.getBooleanCellValue());
} else if (fromCellType == CellType.ERROR) {
newCell.setCellErrorValue(tmpCell.getErrorCellValue());
} else if (fromCellType == CellType.FORMULA) {
newCell.setCellFormula(tmpCell.getCellFormula());
} else {
// nothing29
}
}
}
}
return (HSSFWorkbook)targetWorkBook;
}
Java OPI 两个workbook合并
最新推荐文章于 2023-09-05 22:26:06 发布