Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open EXISTING xls in Apache POI

I have an existing file (C:\wb.xls) that I want to open and make changes to. How in Apachie POI do you open an existing file? All the documentation that I find has to go with creating a new file. And if you know, how do you insert a new row at the top of the xls file or how to autoformat column widths?

like image 694
Marco Polo Avatar asked Jul 09 '13 18:07

Marco Polo


2 Answers

Use one among the following

 XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(xlFileAddress));

OR

 Workbook wb = WorkbookFactory.create(new File(xlFileAddress));

OR

 Workbook wb = WorkbookFactory.create(new FileInputStream(xlFileAddress));

and then use wb for creating/reading/updating sheets/rows/cell whatever you want. For detail visit here. This will definitely help you.

like image 51
Sankumarsingh Avatar answered Nov 04 '22 08:11

Sankumarsingh


Did you try reading the Apache POI HowTo "Reading or modifying an existing file"? That should cover you...

Basically, what you'll want to do is taken from the QuickGuide eg this for loading a File

Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
Sheet s = wb.getSheetAt(0);

// Get the 11th row, creating if not there
Row r1 = s.getRow(10);
if (r1 == null) r1 = s.createRow(10);

// Get the 3rd column, creating if not there
Cell c2 = r1.getCell(2, Row.CREATE_NULL_AS_BLANK);
// Set a string to be the value
c2.setCellValue("Hello, I'm the cell C10!");

// Save
FileOutputStream out = new FileOutputStream("New.xls");
wb.write(out);
out.close();
like image 29
Gagravarr Avatar answered Nov 04 '22 08:11

Gagravarr