Wednesday, December 15, 2010

Read and Write Microsoft Excel ( .xls ) Documents with Jakarta's POI Open source

Reading an Excel Document
Reading an existing Excel document is just as simple as creating one. HSSF provides a custom POIFSFileSystem object that specializes in reading Microsoft's OLE 2 documents. Using the POIFSFileSystem object, you construct an HSSFWorkbook object from a specified Excel document. Here's an example.


//create a POIFSFileSystem object to read the data
POIFSFileSystem fs = new POIFSFileSystem(
new FileInputStream(
"c:/dev/src/customs/Book1.xls"));
Next, create a new workbook from the input stream. You can obtain a reference to any of the worksheets within the workbook. Notice that the worksheet index starts at 0.


// create a workbook out of the input stream
HSSFWorkbook wb = new HSSFWorkbook(fs);
// get a reference to the worksheet
HSSFSheet sheet = wb.getSheetAt(0);
A Little Bit More
Some of you may need to use Java to access Excel from a Web application. In such cases, you may need to construct an Excel document and show it in a browser. That's not difficult but does require a little trick. You send the Excel document as the response, but to make it appear in Excel, you need to set the MIME type of the response to the appropriate type. This method is browser independent. Here's an example:


try {
OutputStream out = res.getOutputStream();

// SET THE MIME TYPE
res.setContentType("application/vnd.ms-excel");

// set content dispostion to attachment in
// case the open/save dialog needs to appear
res.setHeader("Content-disposition",
"inline; filename=sample");
workBook.write(out);
out.flush();
out.close();
} catch (FileNotFoundException fne) {
System.out.println("File not found...");
} catch (IOException ioe) {
System.out.println("IOException..." +
ioe.toString());
}
The following points are important:


Use the MIME type string "application/vnd.ms-excel"
In the response header, the content-disposition entry defines how to deliver this content to the browser. For example, an inline attribute specifies that the browser should present an Open/Save/Cancel dialog before opening this document. The filename attribute specifies a default file name for the document.
This tutorial should help you to get started in the world of Java-to-Microsoft bridges. The POI project offers considerably more than I've discussed here, such as the capability to interact with Microsoft Word and with Adobe's PDF files. The project is very active, so you should monitor the POI project and keep up what's going on.

No comments: