我尝试使用setFillForegroundColor和setFillBackgroundColor来更改excel文件的单元格颜色.
但是,我失败了,我真的不知道问题是什么.我用Google搜索了好几个小时,仍然无法找到正确的方法来设置颜色.
以下是我写的代码:
import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestColor {
public static void main(String[] args) {
File f = new File("test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue("no blue");
// set the color of the cell
XSSFCellStyle style = wb.createCellStyle();
XSSFColor myColor = new XSSFColor(Color.BLUE);
style.setFillForegroundColor(myColor);
style.setFillBackgroundColor(myColor);
cell.setCellStyle(style); // this command seems to fail
try {
FileOutputStream fos = new FileOutputStream(f);
wb.write(fos);
wb.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是最终的结果.
如何将单元格的颜色设置为蓝色?
我正在使用poi-bin-3.12-20150511.zip来自https://poi.apache.org/download.html
McN*_*yyy 20
设置前景色后,您可能需要添加以下行:
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
Run Code Online (Sandbox Code Playgroud)
小智 11
SetFillPattern期望FillPatterType,所以更像是:
style.setFillPattern(FillPatternType.SOLID_FOREGROUND)
Run Code Online (Sandbox Code Playgroud)