如何使用apache POI和java将一个工作簿工作表复制到另一个工作簿工作表

2022-09-03 03:09:01

我有一个带有单张(抽象模型)的excel文件。现在我想将工作表复制到另一个现有工作簿。我该怎么做?


答案 1

为了处理常规样式和数据,我们可以迭代每个单元格。
但是,如果我们启用了公式的单元格,不可编辑的单元格,合并的单元格,那么这是更好的解决方案:
我尝试过像复制工作表这样的事情,但它不起作用。
除此之外,我需要复制一个工作表,其中有一些不可编辑的单元格和公式启用的单元格。

这个解决方案对我有用:
1)复制整个工作簿
2)删除不必要的工作表3)将新工作表添加到上面的书

//input source excel file which contains sheets to be copied
file = new FileInputStream("C:\\SamepleTemplate.xlsx");
workbookinput = new XSSFWorkbook(file);

//output new excel file to which we need to copy the above sheets
//this would copy entire workbook from source
XSSFWorkbook workbookoutput=workbookinput;

//delete one or two unnecessary sheets, you can delete them by specifying the sheetnames
workbook.removeSheetAt(workbook.getSheetIndex(workbook.getSheet(" your sheet name ")));

//if you want to delete more sheets you can use a for to delete the sheets
for (int index=0;index<=5;index++)
{
   workbook.removeSheetAt(index);
}

//To write your changes to new workbook
FileOutputStream out = new FileOutputStream("C:\\FinalOutput.xlsx");
workbookoutput.write(out);
out.close();

答案 2

推荐