A quick guide on generating an excel workbook with the output from an SQL query.
Video guide of the process
Follow the below steps
Add Apache POI dependencies to your pom.xml
1 | <dependency> |
Create a workbook and add the header row.
1 | try (Workbook book = new XSSFWorkbook()) { |
Extract columns from the ResultSet.
1 | ResultSetMetaData rsmd = rs.getMetaData(); |
Populate the header row with the extracted column names.
1 | for (int i = 0; i < columns.size(); i++) { |
Extract the rows from the ResultSet
and populate the workbook.
1 | int rowIndex = 0; |
Writing the excel workbook to filesystem.
1 | try (FileOutputStream fos = new FileOutputStream("FILE_PATH")) { |
You can download this entire class - ResultSetToExcel.java, which is readily usable.
That’s all.
If you have any queries, please do reach out to me via email / phone.