You are on page 1of 14

Creating a Spreadsheet with

Apache POI
Database table data i s often requi red to be presented as an Excel spreadsheet. The
Apache POI HSSF
Excel 2007 .xlsx
consi sts of spreadsheets and an Excel spreadsheet consi sts of rows and cel ls. The
the org.apache.poi.hssf.usermodel package. The data in the Excel spreadsheet
data from a database. In thi s chapter we wi l l di scuss the procedure to create an Excel
spreadsheet from an Oracl e database table. The Excel spreadsheet i s generated i n the
Setting the Environment
The org.apache.poi.hssf.usermodel package cl asses are required to generate
poi-bin-.0.?-FINAL-
?0080?04.zip http.//www.apache.org/dyn/closer.cgi/poi/ and
Instal l the Oracl e database 10g i ncl udi ng sampl e schemas. Create a database
i nstance. Create an exampl e database table from which an Excel spreadsheet wi l l be
generated. The SQL scri pt to create exampl e tabl e Catalog i s l i sted as fol lows:
[ 356 ]
CRFATF TABLF oF.Catalog(CatalogId VARCHAR(25), Journal VARCHAR(25),
Publisher Varchar(25),Fdition VARCHAR(25), Title Varchar(255),
Author Varchar(25));
INSFRT INTo oF.Catalog VALUFS('catalog1', 'oracle Magazine',
'oracle Publishing', 'March~April 2005', 'Starting with oracle ADF
', 'Steve Muench');
INSFRT INTo oF.Catalog VALUFS('catalog2', 'oracle Magazine',
'oracle Publishing','Jan~Feb 2005', 'Understanding optimization',
'Kimberly Floss');
connecti on wi th the Oracl e database for retrievi ng the data for the Excel spreadsheet.
To create a connecti on select the Connections tab, select the Database node i n the
Connections Navigator, ri ght cl i ck on the Database node, and sel ect New Database
Connection. In the Create Database Connection (Type) wi ndow di spl ayed, specify a
Connection Name and set Connection Type to Oracle(JDBC).
[ 357 ]
Cl ick on Next. In the Authentication wi ndow, speci fy the Username and Password
and cl i ck on Next. In the Connection wi ndow, speci fy the Driver type, Host Name,
JDBC Port, SI D and cl i ck on Next.
In the Test wi ndow, cl ick on Test Connection. If a connecti on wi th the database
i s establ i shed a success message is di spl ayed. Cli ck on Finish to compl ete the
Connections Navigator.
[ 358 ]
ApachePOIConnection i s avail abl e as a data source
jdbc/ApachePOIConnectionDS. The data source i s used to retri eve data from
for generati ng an Excel spreadsheet. Select File | New
the New Gallery wi ndow, sel ect General| Applications i n the Categories l isted
and select Application i n the I tems l isted. Cl ick on the OK button. In the Create
Application wi ndow, speci fy an Application Name, sel ect the No Template
Application Template and cl i ck on the OK button. In the Create Project wi ndow,
speci fy a Project Name and cl i ck on the OK
added to the Applications-Navigator.
Applications-Navigator. Sel ect Tools | Project Properties. In
the Project Properties wi ndow, sel ect the Libraries node. Cl ick on the Add Library
button to create a new l ibrary. In the Add Library wi ndow cl i ck on the New button
to add a new l ibrary. In the Create Library wi ndow speci fy a Library Name and
cl i ck on the Add Entry button.
In the Select Path Entry wi ndow sel ect the poi-.0.?-FINAL-?0080?04.jar
and cl i ck on the Select Class Path
node i n the Create Library wi ndow. Cli ck on the OK button i n the Create Library
wi ndow. The Apache POI l i brary is added to the Add Library wi ndow. Cli ck on
the OK button i n the Add Library wi ndow. The Apache POI l i brary is created and
added to the Libraries. The poi-.0.?-FINAL-?0080?04.jar
Add Jar/Directory button.
[ 359 ]
Creating an Excel Spreadsheet
In thi s secti on an Excel spreadsheet wi l l be generated from the exampl e database
Applications Navigator and sel ect New. In
the New Gallery wi ndow sel ect Web Tier | Java Server Pages. In the I tems l isted,
select JSP Page and cl i ck on the OK button. In the Create JSP Wizard sel ect a Web
Application versi on and cl ick on the Next button. In the JSP File wi ndow speci fy a
Next. Cl ick on the Next wi ndow in the Tag Libraries wi ndow.
Sel ect the defaul t options i n the HTML Options page and cli ck on the Next button.
In the Finish wi ndow, cl i ck on Finish
the Applications-Navigator.
[ 360 ]
jdbc/ApachePOIConnectionDS,
web.xml
Add a resource-ref el ement to the web.xml
<resource-ref>
<res-ref-name>jdbc/ApachePOIConnectionDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
In the catalog.jsp an Excel spreadsheet wi ll be created from an Oracl e database
Apache POI HSSF package has cl asses for the different components of an Excel
spreadsheet. Some of the commonl y used cl asses of the Apache POI HSSF package
are l i sted i n the fol l owi ng tabl e.
Class Name Description
HSSFSheet Represents an Excel Spreadsheet.
HSSFHeader
HSSFRow
HSSFCell
HSSFCell Styl e
HSSFFont
HSSFChart Represents a Chart
HSSFDateUti l
HSSFPri ntSetup
<%O page import"org.apache.poi.hssf.usermodel.*, java.sql.*,
java.io.*,javax.naming.InitialContext"%>
Create an Excel styl esheet workbook usi ng the HSSFWorkbook cl ass:
HSSFWorkbook wbnew HSSFWorkbook(),
Next, create an Excel spreadsheet from the HSSFWorkbook
createSheet() method:
HSSFSheet sheetIwb.createSheet("sheetI"),
[ 361 ]
connecti on from the database. Fi rst, create an InitialContext
create a DataSource lookup() method of the InitialContext cl ass
DataSource
usi ng the getConnection() method:
InitialContext initialContext new InitialContext(),
javax.sql.DataSource ds (javax.sql.DataSource)
initialContext.lookup("java.comp/env/jdbc/ApachePOIConnectionDS"),
java.sql.Connection conn ds.getConnection(),
Create a Statement createStatement() method of the Connection
i nterface. Run an SQL query on the Catalog tabl e usi ng the executeQuery()
method of the Statement i nterface to generate a ResultSet
Statement stmtconn.createStatement(),
ResultSet resultSetstmt.executeQuery("Select * from Catalog"),
Create a header row for the Excel spreadsheet usi ng the createRow() method of the
HSSFRow
HSSFRow rowsheetI.createRow(0),
Set the header row cel l val ues correspondi ng to the table columns. Create a cel l
wi th the createCell() method of the HSSFRow cl ass and set the cell value using the
setCellValue()
CatalogId as foll ows:
row.createCell((short)0).setCellValue("CatalogId"),
To add rows to the spreadsheet, iterate over the resul t set and add a row for each of
the tabl e rows. Retri eve the column val ues from the ResultSet and set the val ues i n
the row cell s:
for (int iI,resultSet.next(), i++)
rowsheetI.createRow(i),
row.createCell((short)0).setCellValue(resultSet.getString(I)),
row.createCell((short)I).setCellValue(resultSet.getString(?)),
row.createCell((short)?).setCellValue(resultSet.getString()),
row.createCell((short)).setCellValue(resultSet.getString(4)),
row.createCell((short)4).setCellValue(resultSet.getString(S)),

Create a di rectory C./excel. Create a FileOutputStream to output the Excel


FileOutputStream outputnew FileOutputStream(new File("c./excel/
catalog.xls")),
[ 362 ]
write() method of the
HSSFWorkbook cl ass.
wb.write(output),
The catalog.jsp used to generate an Excel spreadsheet i s l i sted bel ow.
<%O page contentType"text/html,charsetwindows-I?S?"%>
<%O page import"org.apache.poi.hssf.usermodel.*, java.sql.*, java.
io.*,javax.naming.InitialContext"%>
<html>
<head>
<meta http-equiv"Content-Type" content"text/html,
charsetwindows-I?S?">
<title>untitled</title>
</head>
<body><%HSSFWorkbook wbnew HSSFWorkbook(),
HSSFSheet sheetIwb.createSheet("sheetI"),
InitialContext initialContext new InitialContext(),
javax.sql.DataSource ds (javax.sql.DataSource)
initialContext.lookup("java.comp/env/jdbc/ApachePOIConnectionDS"),
java.sql.Connection conn ds.getConnection(),
Statement stmtconn.createStatement(),
ResultSet resultSetstmt.executeQuery("Select * from Catalog"),
HSSFRow rowsheetI.createRow(0),
row.createCell((short)0).setCellValue("CatalogId"),
row.createCell((short)I).setCellValue("Journal"),
row.createCell((short)?).setCellValue("Publisher"),
row.createCell((short)).setCellValue("Edition"),
row.createCell((short)4).setCellValue("Title"),
row.createCell((short)S).setCellValue("Author"),
for (int iI,resultSet.next(), i++)

rowsheetI.createRow(i),
row.createCell((short)0).setCellValue(resultSet.getString(I)),
row.createCell((short)I).setCellValue(resultSet.getString(?)),
row.createCell((short)?).setCellValue(resultSet.getString()),
row.createCell((short)).setCellValue(resultSet.getString(4)),
row.createCell((short)4).setCellValue(resultSet.getString(S)),
row.createCell((short)S).setCellValue(resultSet.getString(8)),

[ 363 ]
FileOutputStream outputnew FileOutputStream(new File("c./excel/
catalog.xls")),
wb.write(output),
output.close(),
resultSet.close(),
stmt.close(),
conn.close(),
%>
</body>
</html>
To run the catalog.jsp
Applications-Navigator and sel ect Run.
[ 364 ]

i s generated:
JDBC 4.0 Version
whi ch may be obtained from: http.//www.oracle.com/technology/software/
tech/java/sqlj_jdbc/htdocs/jdbc_III080.html. Use the ojdbc8.jar
Tools
| Project Properties. In the Project Properties wi ndow, sel ect the Libraries node and
J2SE Version
Connecti on state tracking
Statement pooli ng
[ 365 ]
Connecti on state tracking i s i mpl emented by the connecti on pool manager and is
4.0 provi des the isValid() method i n the Connection i nterface for connecti on state
tracki ng. If the isValid() method returns fal se the connecti on pool manager closes
the connection.
if(!connection.isValid())
connection.close(),
reduced performance due to excessi ve CPU usage. Connecti ons are associ ated wi th
appl i cati on cl ients usi ng cl i ent i nfo properti es. The Connection
4.0 incl udes two new method setClientInfo() and getClientInfo() to set and
get cl ient i nfo properti es. Cl ient i nfo properti es supported by a database may be
retri eved using the getClientInfoProperties() method of the DatabaseMetaData
i nterface as fol l ows:
DatabaseMetaData metaDataconnection.getMetaData(),
ResultSet rsClientInfometadata.getClientInfoProperties(),
The standard cl i ent i nfo properti es ApplicationName, ClientUser, and
ClientHostname may be set on the Connection
conn.setClientInfo("ApplicationName","OracleApp"),
conn.setClientInfo("ClientUser","OracleUser"),
conn.setClientInfo("ClientHostname","OracleHost"),
PreparedStatement
Statement
Statement
the overhead of cl osi ng and openi ng new Statement Statement pool ing
i s i mpl emented usi ng the isPoolable() and setPoolable() methods of the
Statement
if(stmt.isPoolable())
stmt.setPoolable(true),
The Wrapper
Wrapper
CachedRowSet
CallableStatement
[ 366 ]
Connection
DatabaseMetaData
DataSource
FilteredRowSet
JdbcRowSet
JoinRowSet
ParameterMetaData
PreparedStatement
ResultSet
ResultSetMetaData
RowSet
RowSetMetaData
Statement
WebRowSet
pattern as it also extends the Wrapper i nterface. For exampl e, the OracleStatement
Statement i nterface
and thus extends the Wrapper i nterface. The OracleStatement i nterface provides
Statement
OracleStatement i nterface i nstead of the Statement i nterface to run SQL queries.
To create an OracleStatement Statement
wrapper for the OracleStatement i nterface usi ng the isWrapperFor() method. If
a wrapper, unwrap the OracleStatement i nterface to create an OracleStatement
unwrap() method i n the Wrapper i nterface. Subsequentl y i nvoke the
defineColumnType() method of OracleStatement
excepti ons and chai ned causes. Chained excepti ons are excepti ons that are l i nked
for
i terate over chai ned excepti ons as fol l ows:
for(Throwable e . exception )
out.println("Error encountered. " + e),

<%O page contentType"text/html,charsetwindows-I?S?"%>


<%O page import"org.apache.poi.hssf.usermodel.*, java.sql.*, java.
io.*,javax.naming.InitialContext, oracle.jdbc.OracleStatement"%>
[ 367 ]
<html>
<head>
<meta http-equiv"Content-Type" content"text/html,
charsetwindows-I?S?">
<title>untitled</title>
</head>
<body><%
ResultSet resultSet,
HSSFWorkbook wbnew HSSFWorkbook(),
HSSFSheet sheetIwb.createSheet("sheetI"),
InitialContext initialContext new InitialContext(),
javax.sql.DataSource ds (javax.sql.DataSource)
initialContext.lookup("java.comp/env/jdbc/ApachePOIConnectionDS
"),
java.sql.Connection conn ds.getConnection(),
conn.setClientInfo("ApplicationName","OracleApp"),
conn.setClientInfo("ClientUser","OracleUser"),
conn.setClientInfo("ClientHostname","OracleHost"),
Statement stmtconn.createStatement(),
DatabaseMetaData metaDataconnection.getMetaData(),
if(metaData.supportsStatementPooling())
if(stmt.isPoolable())
stmt.setPoolable(true),

Class class Class.forName("oracle.jdbc.OracleStatement"),


if(stmt.isWrapperFor(class))
OracleStatement oracleStmt (OracleStatement)stmt.unwrap(class),
oracleStmt.defineColumnType(I, OracleTypes.VARCHAR),
oracleStmt.defineColumnType(?, OracleTypes.VARCHAR),
oracleStmt.defineColumnType(, OracleTypes.VARCHAR),
oracleStmt.defineColumnType(4, OracleTypes.VARCHAR),
oracleStmt.defineColumnType(S, OracleTypes.VARCHAR),
oracleStmt.defineColumnType(8, OracleTypes.VARCHAR),
resultSetoracleStmt.executeQuery("SELECT * FROM OE.CATALOG"),

HSSFRow rowsheetI.createRow(0),
row.createCell((short)0).setCellValue("CatalogId"),
row.createCell((short)I).setCellValue("Journal"),
row.createCell((short)?).setCellValue("Publisher"),
[ 368 ]
row.createCell((short)).setCellValue("Edition"),
row.createCell((short)4).setCellValue("Title"),
row.createCell((short)S).setCellValue("Author"),
for (int iI,resultSet.next(), i++)

rowsheetI.createRow(i),
row.createCell((short)0).setCellValue(resultSet.getString(I)),
row.createCell((short)I).setCellValue(resultSet.getString(?)),
row.createCell((short)?).setCellValue(resultSet.getString()),
row.createCell((short)).setCellValue(resultSet.getString(4)),
row.createCell((short)4).setCellValue(resultSet.getString(S)),
row.createCell((short)S).setCellValue(resultSet.getString(8)),

FileOutputStream outputnew FileOutputStream(new File("c./excel/


catalog.xls")),
wb.write(output),
output.close(),
resultSet.close(),
stmt.close(),
conn.close(),
%>
</body>
</html>
Summary
In thi s chapter, an Excel spreadsheet was generated from an Oracl e database tabl e
usi ng the Apache POI HSSF API. The Apache POI HSSF API may al so be used to
parse an Excel spreadsheet and subsequently store the spreadsheet i n a database.
connecti on state tracki ng, setti ng of cli ent info properties, statement cachi ng, access
excepti ons faci li ty.

You might also like