19

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?

Marco Polo
  • 267
  • 1
  • 5
  • 16

2 Answers2

23

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.

Sankumarsingh
  • 9,889
  • 11
  • 50
  • 74
  • 2
    Note that [opening from an `InputStream` is slower and requires more memory than opening from a `File`, as explained in the POI docs](http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream) – Gagravarr Jun 30 '16 at 15:52
  • 2
    Note if using maven you need to have dependency of poi-ooxml rather than just poi to use the WorkbookFactory class. – Paul Taylor Mar 15 '17 at 09:12
11

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();
Gagravarr
  • 47,320
  • 10
  • 111
  • 156