Java中如何使用ApachePOI复制excel文件模板(sheet)呢?
下文笔者讲述使用Apache POI的方式复制excel中sheet页的方法及示例分享,如下所示
Apache POI复制sheet页的实现思路
依次获取行和列 然后依次放入到新的sheet中例:
Excel复制sheet页 /** * 复制sheet * @param newSheet * @param oldSheet * @return */ private Sheet copySheet(Sheet newSheet, Sheet oldSheet, Workbook workbook) { //合并单元格 int numMergedRegions = oldSheet.getNumMergedRegions(); for (int i = 0; i < numMergedRegions; i++) { CellRangeAddress mergedRegion = oldSheet.getMergedRegion(i); newSheet.addMergedRegion(mergedRegion); } //增加列宽 int physicalNumberOfCells = oldSheet.getRow(0).getPhysicalNumberOfCells(); for (int i = 0; i < physicalNumberOfCells; i++) { newSheet.setColumnWidth(i, 256 * 15); } //最大获取行数 int maxRowSize = oldSheet.getPhysicalNumberOfRows(); for (int i = 0; i <= maxRowSize; i++) { Row newrow = newSheet.createRow(i); Row oldRow = oldSheet.getRow(i); if (oldRow == null) { continue; } //获取当前行,最大列数 int maxColSize = oldRow.getPhysicalNumberOfCells(); for (int j = 0; j < maxColSize; j++) { Cell newCell = newrow.createCell(j); Cell oldCell = oldRow.getCell(j); if (oldCell == null) { continue; } CellType cellType = oldCell.getCellType(); //此处type类型不只这两种,在此只是列举2种 if ("NUMERIC".equals(cellType.name())) { newCell.setCellValue(oldCell.getNumericCellValue()); } else { newCell.setCellValue(oldCell.getStringCellValue()); } //1.直接copy原cell的样式 //获取原cell的样式 CellStyle oldCellStyle = oldCell.getCellStyle(); newCell.setCellStyle(oldCellStyle); } } return newSheet; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。