java 复制表到已有的excel文件的sheet里面
时间: 2023-08-07 22:04:04 浏览: 223
要将表格复制到已有的Excel文件的工作表中,可以使用Apache POI库来操作Excel文件。可以通过以下步骤来复制表格到已有的Excel文件的工作表中:
1. 打开要编辑的Excel文件,并获取要复制到的工作表。
2. 从要复制的表格中读取数据。
3. 遍历数据并将其复制到工作表中。
4. 保存并关闭Excel文件。
下面是一个简单的Java程序,可以将一个名为“Sheet1”的表格从一个名为“old_file.xlsx”的Excel文件中复制到一个名为“Sheet2”的工作表中:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
public class ExcelCopyTableExample {
public static void main(String[] args) throws Exception {
// Open the Excel file to edit
FileInputStream inputWorkbook = new FileInputStream("old_file.xlsx");
Workbook workbook = WorkbookFactory.create(inputWorkbook);
// Get the sheet to copy to
Sheet sheetToCopyTo = workbook.getSheet("Sheet2");
// Get the table to copy from
Sheet sheetToCopyFrom = workbook.getSheet("Sheet1");
int firstRow = sheetToCopyFrom.getFirstRowNum();
int lastRow = sheetToCopyFrom.getLastRowNum();
int firstCol = sheetToCopyFrom.getRow(firstRow).getFirstCellNum();
int lastCol = sheetToCopyFrom.getRow(firstRow).getLastCellNum();
// Copy the table to the new sheet
for (int i = firstRow; i <= lastRow; i++) {
Row row = sheetToCopyFrom.getRow(i);
Row newRow = sheetToCopyTo.createRow(i - firstRow);
for (int j = firstCol; j < lastCol; j++) {
Cell cell = row.getCell(j);
Cell newCell = newRow.createCell(j);
if (cell != null) {
switch (cell.getCellType()) {
case STRING:
newCell.setCellValue(cell.getStringCellValue());
break;
case NUMERIC:
newCell.setCellValue(cell.getNumericCellValue());
break;
case BOOLEAN:
newCell.setCellValue(cell.getBooleanCellValue());
break;
case FORMULA:
newCell.setCellValue(cell.getCellFormula());
break;
default:
newCell.setCellValue("");
}
}
}
}
// Save the changes to the Excel file
FileOutputStream outputWorkbook = new FileOutputStream("old_file.xlsx");
workbook.write(outputWorkbook);
outputWorkbook.close();
}
}
```
在上面的代码中,我们使用Apache POI库从“old_file.xlsx”文件中读取一个名为“Sheet1”的表格,并将其复制到一个名为“Sheet2”的工作表中。我们遍历原始表格的每一行和每一个单元格,并将它们复制到新的工作表中。最后,我们保存已有的Excel文件。
阅读全文
相关推荐
















