NPOI设置单元格背景色在网上有好多例子都是设置为NPOI内置的颜色值
但是想用rgb值来设置背景色,即:通过HSSFPalette类获取颜色值时会抛出异常:Could not Find free color index
比如:http://www.cnblogs.com/yxhblog/p/6225018.html
最后找到 这个实现后才知道需要额外设置一步
http://www.cnblogs.com/huxiaolin/p/4813518.html
简化后代码如下:
private void button1_Click(object sender, EventArgs e)
{
//创建Excel文件的对象
var book = new HSSFWorkbook();
//添加一个sheet
var sheet1 = book.CreateSheet("Sheet1");
//给sheet1添加第一行的头部标题
var row1 = sheet1.CreateRow(0);
var s = book.CreateCellStyle();
s.FillForegroundColor = GetColourByRGB(book, 82, 238, 172);
s.FillPattern = FillPattern.SolidForeground;
for (int i = 0; i < 10; i++)
{
row1.CreateCell(i).SetCellValue(i);
row1.GetCell(i).CellStyle = s;
}
using (SaveFileDialog sf = new SaveFileDialog())
{
sf.Filter = "表格|*.xls";
sf.AddExtension = true;
if (sf.ShowDialog() == DialogResult.OK)
{
//创建一个文档流对象
using (FileStream fs = new FileStream(sf.FileName, FileMode.Create))
{
//将内存里面的文档对象,写入到一个文档流中
book.Write(fs);
}
}
}
}
private short GetColourByRGB(HSSFWorkbook workbook, byte r, byte g, byte b)
{
var palette = workbook.GetCustomPalette();
var hssfColor = palette.FindColor(r, g, b);
if (hssfColor == null)
{
palette.SetColorAtIndex(HSSFColor.Lavender.Index, r, g, b);
hssfColor = palette.GetColor(HSSFColor.Lavender.Index);
}
if (hssfColor != null)
{
return hssfColor.Indexed;
}
else
{
return short.MinValue;
}
}