且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将表单添加到现有的Excel文件中

更新时间:2022-10-20 12:54:24

如果您使用 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.