0

I got a small problem while working with a project.

I already have an excel file with some sheets in it.

Whenever I need to create a new excel file sheet with a particular name, I need to check if there's already a sheet with that name,

If it is so,

1.Then I need to delete it(thus deleting any old info),note the position of the sheet and create a new one with the same name at the same position

If not

1.Then i need to create a new sheet

I am stuck with it.Could anyone give some insights/some steps to accomplishing the task? Could I do the same with Apache POI or conveniently any other API?

Thanks in advance.I am supposed to use java as a medium while doing this.

ranjithnori
  • 183
  • 3
  • 15

4 Answers4

3

If you are using POI, you can get no. of sheets in xls file by workbook.getNumberOfSheets().

You can iterate over them using regular for loop and check sheet names, if name matches with sheet name, you can delete it using workbook.removeSheetAt(index). And now you can create new sheet with same name and at given index.

Hope this helps.

Abdul
  • 41
  • 5
0

xlsx4j is something you may want to look at

click here for more info

MaheshVarma
  • 2,081
  • 7
  • 35
  • 58
0

The folloiwng code from JExcelAPI should work....

InputStream inp = new FileInputStream("workbook.xls");
//InputStream inp = new FileInputStream("workbook.xlsx");

Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt("sheet_name");
if(sheet != null)
{
 wb.removeSheet(index);
 //further functionality
}
else
{
  //code if sheet does not exists
}
Pavan Kumar K
  • 1,360
  • 9
  • 11
0

apache-poi could menage it.

Use: HSSFWorkbook.createSheet(sheetName) to create the new sheet. If it throws java.lang.IllegalArgumentException then it already exists, so you can find and delete it:

HSSFWorkbook.getSheetIndex(sheetName) to get index and HSSFWorkbook.removeSheetAt(index). Finally you can move your new sheet at desired position by: HSSFWorkbook.setSheetOrder(sheetName, position)

mauretto
  • 3,183
  • 3
  • 27
  • 28