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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3333021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:18:24  来源:igfitidea点击:

how to copy one workbook sheet to another workbook sheet using apache POI and java

javaapache-poi

提问by Saravanan

I have one excel file with single sheet (abstract model). Now I want to copy the sheet to another existing workbook. How can I do this?

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

回答by Ajay

For processing regular styles and data we could iterate through each cells.
But if we have formula enabled cell,non editable cells, merged cell then this is the better solution to go for:
I have tried something like copying sheets but it didn't worked.
In addition with that i need to copy a sheet in which there are some non editable cells and formula enabled cells too.

为了处理常规样式和数据,我们可以遍历每个单元格。
但是,如果我们有启用公式的单元格、不可编辑的单元格、合并的单元格,那么这是更好的解决方案:
我尝试过复制工作表之类的东西,但没有奏效。
除此之外,我还需要复制一个工作表,其中也有一些不可编辑的单元格和启用公式的单元格。

This solution worked for me:
1)copy the entire workbook
2)delete unnecessary sheets 3)add your new sheets to above book

这个解决方案对我有用:
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();