将表单添加到现有的Excel文件中 [英] Add a sheet into existing excel file
问题描述
我想将一个工作表添加到现有的excel文件。我怎样才能做到这一点?我正在处理一个硒项目,我想将所有自动化结果表添加到单个excel文件中。现在我可以为每个工作表创建新的excel文件。
如果您使用 Apache POI
要打开现有工作表或分别创建新工作表:
final File file =/tmp/sheet.xls;
最终HSSFWorkbook工作簿;
if(file.exists()== false){
System.out.println(创建新的工作簿+文件+');
workbook = new HSSFWorkbook();
} else {
System.out.println(追加到现有工作簿+文件+');
final InputStream is = new FileInputStream(file);
try {
workbook = new HSSFWorkbook(is);
} finally {
is.close();
}
}
要检查是否存在表单以创建您可以使用以下特征:
int sheetIndex = 1;
while(workbook.getSheet(Sheet+ sheetIndex)!= null){
sheetIndex ++;
}
然后您可以通过调用 createSheet
:
HSSFSheet sheet = workbook.createSheet(Sheet+ sheetIndex);
在这种情况下,工作表名称是Sheet 1,Sheet 2等。 p>
I want to add a sheet to existing excel file. How can I do that? I am working on one selenium project and I want to add all of my automation result sheets into single excel file. Right now I am able to create new excel file for each sheet.
If you use Apache POI
from Java:
To open an existing sheet or to create a new sheet respectively:
final File file = "/tmp/sheet.xls";
final HSSFWorkbook workbook;
if (file.exists() == false) {
System.out.println("Creating a new workbook '" + file + "'");
workbook = new HSSFWorkbook();
} else {
System.out.println("Appending to existing workbook '" + file + "'");
final InputStream is = new FileInputStream(file);
try {
workbook = new HSSFWorkbook(is);
} finally {
is.close();
}
}
To check whether a sheet exists in order to create a unique sheet name, you could use something like this:
int sheetIndex = 1;
while (workbook.getSheet("Sheet " + sheetIndex) != null) {
sheetIndex++;
}
then you can add a sheet by calling createSheet
:
HSSFSheet sheet = workbook.createSheet("Sheet " + sheetIndex);
In this case the sheet names are "Sheet 1", "Sheet 2", etc.
这篇关于将表单添加到现有的Excel文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!