javaexcelfontspoi-hssf

how to set cell style without HSSFWorkbook instance?


I wanted to set font of the title row in a spreadsheet bold. I was able to do that in my main function with the following code:

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet dataSheet = workbook.createSheet("Data");
HSSFCellStyle fontStyle = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
fontStyle.setFont(font);
Row row = dataSheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(fontStyle);
cell.setCellValue("ID");

Since createCellStyle is method of HSSFWorkbook, if I write to the sheet by calling a function which takes the sheet but not the workbook as parameter, how do I set the cell style?

public class SummaryXlsCreator {
    public static void main(String[] args) {
        HSSFWorkbook workbook = new    HSSFWorkbook();
        HSSFSheet dataSheet = workbook.createSheet("Data");
        writeCDMarker(dataSheet);
    }

    public static void writeCDMarker(HSSFSheet sheet) {
        int rownum = 0;
        int cellnum = 0;
        Row row = sheet.createRow(rownum++);
        Cell cell = row.createCell(cellnum++);
        // write first row of sheet "Data"
        cell.setCellValue("ID");
    }

Solution

  • Use getWorkbook() to get the parent and proceed with the existing code.

    sheet.getWorkbbok().createCellStyle();
    

    https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html