Export Excel Files in Java Using Apache POI
This article demonstrates how to use Apache POI in Java to export collections of JavaBean objects to Excel files, covering generic reflection‑based implementation, styling, handling of dates, booleans, images, and integration with a servlet for download.
In web development, exporting data to Excel is a common requirement for reporting and printing, and this guide shows how to achieve it using Apache POI.
First, download the POI library (e.g., version 3.0.2) and add the required JAR files to the classpath.
Two simple JavaBean classes are defined: Student (id, name, age, sex, birthday) and Book (bookId, name, author, price, isbn, pubName, preface). These classes provide standard getters and setters.
The core ExportExcel<T> class uses Java reflection to iterate over a collection of any JavaBean‑style objects and write their fields to an Excel sheet. It creates a workbook, defines header and data cell styles, adds optional comments, and supports various data types:
Boolean values are converted to "男"/"女".
Date values are formatted with a configurable pattern.
byte[] values are treated as JPEG images and inserted into cells.
Other types are written as strings, with numeric strings automatically parsed as numbers.
The class provides overloaded exportExcel methods that accept a title, column headers, the data collection, an OutputStream , and an optional date pattern.
A main method demonstrates usage: it creates sample Student and Book lists, populates them, and calls exportExcel to generate a.xls and b.xls files.
For web deployment, a servlet example ( ExcelServlet ) shows how to invoke the exporter and stream the generated file to the client with proper HTTP headers, enabling a download dialog.
Finally, the article reminds you to register the servlet in web.xml and place a small book image ( book.jpg ) under /WEB-INF/ for the image‑embedding feature to work.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.