poi4.0复制sheet页到新的excel中并且复制样式
时间: 2023-08-17 09:05:05 浏览: 236
poi复制excel的sheet页
可以使用Apache POI 4.0中的`Workbook.createSheet()`方法创建新的工作表,然后使用`Sheet.copy()`方法复制原始工作表的内容和格式。下面是示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CopySheetExample {
public static void main(String[] args) {
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sourceSheet = workbook.createSheet("Source Sheet");
Sheet targetSheet = workbook.createSheet("Target Sheet");
// 添加示例数据和样式
addExampleData(sourceSheet);
addExampleStyle(sourceSheet);
// 复制原始工作表到目标工作表
copySheet(sourceSheet, targetSheet);
// 保存工作簿
try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {
workbook.write(outputStream);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void addExampleData(Sheet sheet) {
Row row1 = sheet.createRow(0);
Cell cell1 = row1.createCell(0);
cell1.setCellValue("Name");
Cell cell2 = row1.createCell(1);
cell2.setCellValue("Age");
Row row2 = sheet.createRow(1);
Cell cell3 = row2.createCell(0);
cell3.setCellValue("John");
Cell cell4 = row2.createCell(1);
cell4.setCellValue(30);
}
private static void addExampleStyle(Sheet sheet) {
CellStyle style = sheet.getWorkbook().createCellStyle();
style.setBorderBottom(CellStyle.BORDER_THICK);
style.setBorderTop(CellStyle.BORDER_THICK);
style.setBorderLeft(CellStyle.BORDER_THICK);
style.setBorderRight(CellStyle.BORDER_THICK);
for (Row row : sheet) {
for (Cell cell : row) {
cell.setCellStyle(style);
}
}
}
private static void copySheet(Sheet sourceSheet, Sheet targetSheet) {
targetSheet.setZoom(sourceSheet.getZoom());
for (Row row : sourceSheet) {
Row newRow = targetSheet.createRow(row.getRowNum());
for (Cell cell : row) {
Cell newCell = newRow.createCell(cell.getColumnIndex(), cell.getCellType());
newCell.setCellStyle(cell.getCellStyle());
switch (cell.getCellType()) {
case BOOLEAN:
newCell.setCellValue(cell.getBooleanCellValue());
break;
case NUMERIC:
newCell.setCellValue(cell.getNumericCellValue());
break;
case STRING:
newCell.setCellValue(cell.getStringCellValue());
break;
case FORMULA:
newCell.setCellFormula(cell.getCellFormula());
break;
case BLANK:
// 什么也不做
break;
case ERROR:
newCell.setCellErrorValue(cell.getErrorCellValue());
break;
}
}
}
}
}
```
此代码将在工作簿中创建一个名为“Source Sheet”的工作表,将样式应用于其单元格,并将其复制到名为“Target Sheet”的新工作表中。保存之后,您将在Excel中看到两个相同的工作表,均包含示例数据和样式。
阅读全文