Excel Sheet From Database Without Use of POJO
This program creates an excel sheet by simply passing a SQL query to the database and replicating the view to the excel grid.
Join the DZone community and get the full member experience.Join For Free
This application establishes connection before the class is being loaded in the memory by the class loader. Once the predefined Query is executed the ResultSet structure is acquired along with some MetaData.
MetaData the name suggests data about data, this is what helps to define the structure of the ExcelSheet.
From ResultSetMetaData class number of columns are determined.
Hence if the number of columns is Unity(1) then the getColumnName() is called once, else if greater than Unity then the array is looped to obtain the columnNames.
The number of columnNames will be equal to the size of the record holding values that are pertaining to those columnNames.
To extract the record from the ResultSet the following steps occur "while" looping over the ResultSet.
For every invocation of next( ) that returns true.
1) Create an array of length equal to the number of columns found from ResultSetMetaData getColumnCount method, that will hold a record.
2) Fill every index of the created array by invoking the getStringMethod parameterized with the index in the loop.
3) Add the array to a LinkedList.
Once the LinkedList has the entire set of rows that were found in the ResultSet class.
A TreeMap holds the structure of the data to be written into the grid of the ExcelSheet.
The first Key is set for columnNames array.From the next Key to the end of the LinkedList carrying the records iteration starts a new Row is created.
For every row having cells the row's data is looped and the index of the cells are incremented
as the array's index data gets accessed linearly. Depending on the DataType of the object the value is casted.
Once the Workbook has the data set in the grid.FileOutstream writes the data to the file in the disk.
Opinions expressed by DZone contributors are their own.