Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a CellStyle library in Apache POI

My system produces lots of different Excel reports using Apache POI from Java.

A lot of these reports share the same styles.

I have created a CellStyle library for use by all of the reports. I wondered if there was a neater way.

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;

public class CellStyles {
    CellStyle headingCellStyle = null;
    Workbook wb;

    public CellStyles(Workbook wb) {
        this.wb = wb;
    }

    public CellStyle getHeadingCellStyle() {
        if (headingCellStyle == null) {
            headingCellStyle = wb.createCellStyle();
            headingCellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
            headingCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        }
        return headingCellStyle;
    }

}

and then calling it

Workbook wb = new XSSFWorkbook(inputStream); // XSSF for .xlsm
CellStyles cs = new CellStyles(wb);


CellUtil.getCell(myRow, 2).setCellStyle(cs.getHeadingCellStyle());
like image 458
gordon613 Avatar asked May 11 '14 16:05

gordon613


1 Answers

I think that given its simplicity this solution it is good.

Unfortunately in POI CellStyle needs to be created from Workbook so you can't really avoid passing wb as a parameter in some way.

In addition to your implementation you might try to expose in CellStyles a bunch of static methods taking wb as a parameter and returning the style, so that you don't need to pass cs object around in your code. Though I wouldn't say it's worth it as to do it properly you'd need to maintain the static cache of Map[Workbook, CellStyles] mappings, which would use for returning the style.

Lazy initialization of styles works well too and allows you to avoid creating duplicate styles, though it would be better to keep styles private i.e. private CellStyle headingCellStyle = null; to ensure nothing can change the style assignment outside the class and null-valued headerCellStyle won't be used by accident.

like image 113
Norbert Radyk Avatar answered Sep 20 '22 06:09

Norbert Radyk