如何在没有 HSSFWorkbook 实例的情况下设置单元格样式?

how to set cell style without HSSFWorkbook instance?

我想将标题行的字体设置为展开sheet粗体。我能够使用以下代码在我的主要功能中做到这一点:

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");

由于 createCellStyle 是 HSSFWorkbook 的方法,如果我通过调用以 sheet 而不是工作簿作为参数的函数写入 sheet,我该如何设置单元格样式?

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");
    }

使用 getWorkbook() 获取父级并继续现有代码。

sheet.getWorkbbok().createCellStyle();

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

您可以使用静态 CellUtil.setCellStyleProperties(Cell cell, Map<String, Object> properties) 来格式化您的单元格,而无需引用您的工作簿或 sheet。

用法示例:

// Format cell into date time format with "m/d/yy h:mm", 
// which is converted to user's locale in Excel. 
CellUtil.setCellStyleProperties(cell, Collections.singletonMap(CellUtil.DATA_FORMAT, (short) 22));