Skip to content

Instantly share code, notes, and snippets.

@wytten
Last active June 1, 2020 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wytten/32be05889f84673d6187561699eeb253 to your computer and use it in GitHub Desktop.
Save wytten/32be05889f84673d6187561699eeb253 to your computer and use it in GitHub Desktop.
Turn your JAVA Beans into a POI Excel Spreadsheet (@author Jeff Byrd)
/**
* Source: Turn your JAVA Beans into a POI Excel Spreadsheet http://www.dominotricks.com/?p=115
*
* @author Jeff Byrd
*
*/
public class Bean2Excel {
private HSSFWorkbook workbook;
private HSSFFont boldFont;
private HSSFDataFormat format;
public static void main(String[] args) {
// Used to create the hire dates
SimpleDateFormat sdf = new SimpleDateFormat("yyyy, MM, dd");
try {
// Create the report object
Bean2Excel oReport = new Bean2Excel();
// Create a list of employee data
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee(100, "Abe Adams", sdf.parse("2009, 12, 1"), 10000.00));
employees.add(new Employee(101, "Betty Barnes", sdf.parse("2010, 11, 1"), 11000.00));
employees.add(new Employee(102, "Caleb Crown", sdf.parse("2011, 10, 1"), 12000.00));
employees.add(new Employee(103, "Dirk Daniels", sdf.parse("2012, 09, 1"), 13000.00));
// Create an array of report column objects
ReportColumn[] reportColumns = new ReportColumn[] { new ReportColumn("id", "Id", FormatType.INTEGER),
new ReportColumn("name", "Last Name", FormatType.TEXT),
new ReportColumn("hireDate", "Hire Date", FormatType.DATE),
new ReportColumn("salary", "Salary", FormatType.MONEY) };
// Create a worksheet with our employee data and report columns
oReport.addSheet(employees, reportColumns, "sheet1");
// Set the Hire Date Column text to Bold and background to Green
reportColumns[2].setColor(HSSFColor.GREEN.index);
// Add a 2nd sheet with the same data.
oReport.addSheet(employees, reportColumns, "sheet2");
// Create an output stream to write the report to.
OutputStream output = new FileOutputStream("c:\\temp\\report1.xls");
// Write the report to the output stream
oReport.write(output);
// Finally, save the report
output.close();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Bean2Excel() {
workbook = new HSSFWorkbook();
boldFont = workbook.createFont();
boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
format = workbook.createDataFormat();
}
public void addSheet(List<?> data, ReportColumn[] columns, String sheetName) {
HSSFSheet sheet = workbook.createSheet(sheetName);
int numCols = columns.length;
int currentRow = 0;
HSSFRow row;
try {
// Create the report header at row 0
row = sheet.createRow(currentRow);
// Loop over all the column beans and populate the report headers
for (int i = 0; i < numCols; i++) {
// Get the header text from the bean and write it to the cell
writeCell(row, i, columns[i].getHeader(), FormatType.TEXT, null, this.boldFont);
}
currentRow++; // increment the spreadsheet row before we step into
// the data
// Write report rows
for (int i = 0; i < data.size(); i++) {
// create a row in the spreadsheet
row = sheet.createRow(currentRow++);
// get the bean for the current row
Object bean = data.get(i);
// For each column object, create a column on the current row
for (int y = 0; y < numCols; y++) {
Object value = PropertyUtils.getProperty(bean, columns[y].getMethod());
writeCell(row, y, value, columns[y].getType(), columns[y].getColor(), columns[y].getFont());
}
}
// Autosize columns
for (int i = 0; i < numCols; i++) {
sheet.autoSizeColumn((short) i);
}
} catch (Exception e) {
System.err.println("Caught Generate Error exception: " + e.getMessage());
}
}
public HSSFFont boldFont() {
return boldFont;
}
public void write(OutputStream outputStream) throws Exception {
workbook.write(outputStream);
}
private void writeCell(HSSFRow row, int col, Object value, FormatType formatType, Short bgColor, HSSFFont font)
throws Exception {
HSSFCell cell = HSSFCellUtil.createCell(row, col, null);
if (value == null) {
return;
}
if (font != null) {
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
cell.setCellStyle(style);
}
switch (formatType) {
case TEXT:
cell.setCellValue(value.toString());
break;
case INTEGER:
cell.setCellValue(((Number) value).intValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT,
HSSFDataFormat.getBuiltinFormat(("#,##0")));
break;
case FLOAT:
cell.setCellValue(((Number) value).doubleValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT,
HSSFDataFormat.getBuiltinFormat(("#,##0.00")));
break;
case DATE:
cell.setCellValue((Date) value);
HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT,
HSSFDataFormat.getBuiltinFormat(("m/d/yy")));
break;
case DATE_TIME:
cell.setCellValue((Date) value);
HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT,
HSSFDataFormat.getBuiltinFormat(("m/d/yy h:mm"))); // TODO: seconds (not easy)
break;
case MONEY:
cell.setCellValue(((Number) value).intValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT, format.getFormat("$#,##0.00;$#,##0.00"));
break;
case PERCENTAGE:
cell.setCellValue(((Number) value).doubleValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT, HSSFDataFormat.getBuiltinFormat("0.00%"));
}
if (bgColor != null) {
HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.FILL_FOREGROUND_COLOR, bgColor);
HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.FILL_PATTERN, HSSFCellStyle.SOLID_FOREGROUND);
}
}
public enum FormatType {
TEXT,
INTEGER,
FLOAT,
DATE,
DATE_TIME,
MONEY,
PERCENTAGE
}
}
/**
* Source: Turn your JAVA Beans into a POI Excel Spreadsheet http://www.dominotricks.com/?p=115
*
* @author Jeff Byrd
*
*/
public class Employee {
private String m_name;
private Integer m_id;
private Date m_hireDate;
private Double m_salary;
public Employee() {
}
public Employee(Integer id, String name, Date hiredate, Double salary) {
this.m_id = id;
this.m_name = name;
this.m_hireDate = hiredate;
this.m_salary = salary;
}
public String getName() {
return m_name;
}
public void setName(String name) {
this.m_name = name;
}
public Integer getId() {
return m_id;
}
public void setId(Integer id) {
this.m_id = id;
}
public Date getHireDate() {
return m_hireDate;
}
public void setHireDate(Date hireDate) {
this.m_hireDate = hireDate;
}
public Double getSalary() {
return m_salary;
}
public void setSalary(Double salary) {
this.m_salary = salary;
}
}
/**
* Source: Turn your JAVA Beans into a POI Excel Spreadsheet http://www.dominotricks.com/?p=115
*
* @author Jeff Byrd
*
*/
public class ReportColumn {
private String m_method;
private String m_header;
private FormatType m_type;
private HSSFFont m_font;
private Short m_color;
public ReportColumn(String method, String header, FormatType type, HSSFFont font, Short color) {
this.m_method = method;
this.m_header = header;
this.m_type = type;
this.m_font = font;
this.m_color = color;
}
public ReportColumn(String method, String header, FormatType type, HSSFFont font) {
this(method, header, type, font, null);
}
public ReportColumn(String method, String header, FormatType type, Short color) {
this(method, header, type, null, color);
}
public ReportColumn(String method, String header, FormatType type) {
this(method, header, type, null, null);
}
public String getMethod() {
return m_method;
}
public void setMethod(String method) {
this.m_method = method;
}
public String getHeader() {
return m_header;
}
public void setHeader(String header) {
this.m_header = header;
}
public FormatType getType() {
return m_type;
}
public void setType(FormatType type) {
this.m_type = type;
}
public HSSFFont getFont() {
return m_font;
}
public void setFont(HSSFFont m_font) {
this.m_font = m_font;
}
public Short getColor() {
return m_color;
}
public void setColor(Short m_color) {
this.m_color = m_color;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment