如何更改文本颜色和填充颜色

如何将标题字体颜色更改为白色和填充绿色? 这些是我正在使用的类:

import static org.apache.poi.ss.usermodel.CellStyle.* import static org.apache.poi.ss.usermodel.IndexedColors.* import org.apache.poi.hssf.usermodel.* import org.apache.poi.hssf.usermodel.HSSFWorkbook import org.apache.poi.ss.usermodel.Cell import org.apache.poi.ss.usermodel.CellStyle import org.apache.poi.ss.usermodel.Row import org.apache.poi.ss.usermodel.Sheet import org.apache.poi.ss.usermodel.Workbook import org.apache.poi.ss.usermodel.Font 

这是代码,我相信,它必须插入。

 Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD) CellStyle headerStyle = wb.createCellStyle() headerStyle.setFont(headerFont) cellMOPID.setCellStyle(headerStyle) cellType.setCellStyle(headerStyle) cellStatus.setCellStyle(headerStyle) cellState.setCellStyle(headerStyle) cellStartDate.setCellStyle(headerStyle) cellEndDate.setCellStyle(headerStyle) cellDesc.setCellStyle(headerStyle) 

  HSSFCellStyle cellStyle = workBook.createCellStyle(); HSSFFont font = wb.createFont(); font.setFontName(XSSFFont.DEFAULT_FONT_NAME); font.setFontHeightInPoints((short)10); font.setColor(IndexedColors.BLUE.getIndex()); cellStyle.setFont(font); //the version i am using is poi-3.8 

如果你想将颜色设置为简单的单元格样式…你可以编写类似的代码。

  cell.setCellValue("Header Text"); XSSFCellStyle headerStyle = wb.createCellStyle(); Font headerFont = wb.createFont(); headerStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); headerFont.setColor(IndexedColors.WHITE.getIndex()); headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); headerStyle.setFont(headerFont); cell.setCellStyle(headerStyle); 

这将用绿色填充单元格,字体将是粗体白色

对于xls文件,我检查了以下内容,并且在我的结束时工作正常。

我需要导入以下内容:

 import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; 

而这段代码如下:

  FileInputStream fin = new FileInputStream (XLSFileAddress); HSSFWorkbook wb = new HSSFWorkbook(fin); HSSFCell cell=wb.getSheetAt(2).getRow(0).getCell(0); cell.setCellValue("Header Text"); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); CellStyle headerStyle = wb.createCellStyle(); headerStyle.setFont(headerFont); headerStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); headerFont.setColor(IndexedColors.WHITE.getIndex()); headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); cell.setCellStyle(headerStyle); FileOutputStream fileOut = new FileOutputStream(XLSFileAddress); wb.write(fileOut); fileOut.close(); 

此代码的输出是索引为2的第一行表格的第一个单元格,将显示文本“标题文本”单元格颜色为绿色,文本颜色为白色,带粗体字体

我正在使用apache POI 3.9。