您的位置:首页 > 编程语言 > Java开发

Java poi 自定义RGB颜色

2017-08-16 09:55 239 查看

最近有个需求,要求将数据插入创建的Excel中,并将第一行某些列背景颜色做自定义RGB,在网上找了一些,结合自己本身需求,写了一些,这是其中自己感觉比较方便的

用到的java尬包

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;


public static void createExcel()
{
String toFilePath = "D:\\Excel\\" + "OOB.xls";
String sheetName = "oob.xls";
String[] titleRow =
{ "第一列", "第二列", "第三列", "第四列" };
// 创建workbook
HSSFWorkbook workbook = new HSSFWorkbook();
// 添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
HSSFSheet sheet1 = workbook.createSheet(sheetName);
FileOutputStream fo = null;
BufferedOutputStream out = null;
File file = new File(toFilePath);
if (!file.exists())
{
boolean mkdirs = file.mkdirs();
}
if (new File(toFilePath).exists())
{
new File(toFilePath).delete();
}
try
{
fo = new FileOutputStream(toFilePath);
out = new BufferedOutputStream(fo);
// 添加表头
Row row = sheet1.createRow(0); // 创建第一行
for (int i = 0; i < titleRow.length; i++)
{
String string = titleRow[i];
HSSFCellStyle style = workbook.createCellStyle();
//设置字体加粗
HSSFFont font = workbook.createFont();
//粗体显示
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体格式
font.setFontName("宋体");
style.setFont(font);
// 设置背景颜色IndexedColors.LIGHT_YELLOW.getIndex()这个是JAVA提供的,是一个short类型,
//我们需要做的就是用我们自定义RGB将这个颜色替换掉
style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
//自定义RGB
HSSFPalette customPalette = workbook.getCustomPalette();
//这里的setColorAtIndex方法需要的参数是(short index, byte red, byte green, byte blue)
//这里的short我们直接用Java给我们提供的,我看有些人用的是自定义的short那个会有问题的
customPalette.setColorAtIndex(IndexedColors.LIGHT_YELLOW.getIndex(), (byte) 255,
(byte) 230, (byte) 153);
// 设置列宽
sheet1.setColumnWidth(i, 9000);

// 创建第i列
HSSFCell cell = (HSSFCell) row.createCell(i);
cell.setCellValue(titleRow[i]);
//让设置生效
cell.setCellStyle(style);
}
fo = new FileOutputStream(toFilePath);
out = new BufferedOutputStream(fo);
workbook.write(out);
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
out.flush();
} catch (IOException e)
{
e.printStackTrace();
}
}
}


以上就是设置某一列的自定义RGB的实现方法,新人第一次发表,求轻喷
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: