带有背景颜色的粗体文本样式的Excel代码行

我GOOGLE了一些代码,发现一些答案,但无法得到我的Excel文件输出在粗体和设置背景颜色。 我已经尝试了下面的代码。 你能告诉我我哪里错了吗? 请看一下。 谢谢。

仅供参考:我打算用大胆的蓝色或任何浅色背景制作第一排。 如果你知道请帮助代码。

// Excel file generation code HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Readings"); CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setFontHeightInPoints((short)11); font.setFontName(HSSFFont.FONT_ARIAL); font.setBoldweight(HSSFFont.COLOR_NORMAL); font.setBold(true); font.setColor(HSSFColor.DARK_BLUE.index); style.setFont(font); // Freeze 1st Row sheet.createFreezePane(0, 1); HSSFRow row = sheet.createRow(1); HSSFRow rowhead = sheet.createRow((short) 0); rowhead.setRowStyle(style); rowhead.createCell(0).setCellValue("RUN"); rowhead.createCell(1).setCellValue("NUMBER"); 

你在做下面的错误:

1-您不设置任何背景颜色;

2-创build新的单元格时,它们会覆盖行的样式,因此您需要为每个新创build的单元格设置样式;

以下是工作代码:

 FileOutputStream fileOut = new FileOutputStream("poi-test.xls"); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Readings"); CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setFontHeightInPoints((short)11); font.setFontName(HSSFFont.FONT_ARIAL); font.setBoldweight(HSSFFont.COLOR_NORMAL); font.setBold(true); font.setColor(HSSFColor.DARK_BLUE.index); style.setFont(font); //Add these lines style.setFillForegroundColor(IndexedColors.AQUA.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); sheet.createFreezePane(0, 1); // Freeze 1st Row sheet.createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) HSSFRow rowhead = sheet.createRow((short) 0); rowhead.setRowStyle(style); //Set the cell0 Style HSSFCell cell0 = rowhead.createCell(0); cell0.setCellStyle(style); cell0.setCellValue("ROW"); //Set the cell1 Style HSSFCell cell1 = rowhead.createCell(1); cell1.setCellStyle(style); cell1.setCellValue("NUMBER"); workbook.write(fileOut); 

文件输出:

结果

首先删除font.setBoldweight(HSSFFont.COLOR_NORMAL); 。 COLOR_NORMAL不是一个真正的粗体,而是一种颜色。 font.setBold(true); 应该足以大胆的文字。

你也需要添加一些属性到你的风格来获得背景颜色。 这是令人困惑的部分。 该方法是使用填充。 填充具有不同于其他单元格的前景和背景颜色。 要获得可靠的填充,您需要使用:

 style.setForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); 

请注意,这将填充的前景颜色设置为浅蓝色。 由于填充具有坚实的前景,这就是你所需要的。 如果您select其中一种图案填充,则还需要为填充设置背景颜色。 填充本身就是单元格背景。