Add sheet to existing excel file

I want to add a sheet to an existing excel file. How can i do this? I am working on one selenium project and I want to add all my automation result sheets to a single excel file. Now I can create a new excel file for each sheet.

+1
source share
3 answers

If you are using Apache POIfrom Java:

To open an existing sheet or 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 if a sheet exists to create a unique sheet name, you can 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.

+1
source

VBA :

Sheets.Add
+2
Worksheets.Add

(in automation it is best to be specific)

You need to save the link to this new worksheet. In VBA, it will be

Set wsRef = Worksheets.Add
+2
source

All Articles