【转】NPOI自定义单元格背景颜色
2017-06-27 10:57 杨新华 阅读(3664) 评论(0) 收藏 举报经常在NPOI群里聊天时发现有人在问NPOI设置单元格背景颜色的问题,而Tony Qu大神的博客里没有相关教程,刚好最近在做项目时研究了一下这一块,在这里总结一下。
在NPOI中默认的颜色类是HSSFColor,如果要使用NPOI中的颜色就必须想办法转化为HSSFColor。分析了一下原代码,HSSFColor内置了几十种颜色,都是用内部类继承HSSFColor这个类来定义的。那么除非去修改源代码,否则是不能以这种方式来使用自定义颜色的。
除了继承的方式外,还有另外一种方式使用HSSFColor。答案就是从调色板中获取颜色。从调色板中获取颜色的主要步骤是:1、将颜色的RGB值添加进调色板HSSFPalette中。2、调用HSSFPalette中FindColor方法获取HSSFColor实例。3、在需要使用颜色的地方使用HSSFColor的GetIndex方法获取index值。以下是实现相关源代码:
int StartColIndex = 0;
    int rowIndex = 0;    int colIndex = StartColIndex;    HSSFWorkbook hssfWorkbook = new HSSFWorkbook();    ISheet sheet = hssfWorkbook.CreateSheet("Sheet1");    IRow row;    ICell cell;    HSSFPalette palette = hssfWorkbook.GetCustomPalette();    List<Color> colorList = new List<Color>();    Random random = new Random(Guid.NewGuid().GetHashCode());    for (int i = 0; i < random.Next(100, 200); i++)    {        colorList.Add(Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)));    }    short FIRST_COLOR_INDEX = (short)0x8;    for (int i = 0; i < colorList.Count; i++)    {        if ((short)(FIRST_COLOR_INDEX + i) > (short)0x40)        {            break;        }        //index的取值范围 0x8 - 0x40        palette.SetColorAtIndex((short)(FIRST_COLOR_INDEX + i), colorList[i].R, colorList[i].G, colorList[i].B);    }    for (int i = 0; i < colorList.Count; i++)    {        if (i >= (short)(0x40 - 0x8))        {            break;        }        colIndex = StartColIndex;        row = sheet.CreateRow(rowIndex);        cell = row.CreateCell(colIndex);        ICellStyle colorStyle = hssfWorkbook.CreateCellStyle();        colorStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;        var v1 = palette.FindColor(colorList[i].R, colorList[i].G, colorList[i].B);        if (v1 == null)        {            throw new Exception("Color is not in Palette");        }        colorStyle.FillForegroundColor = v1.GetIndex();        cell.CellStyle = colorStyle;        colIndex++;        rowIndex++;    }    string fileName = @"test.xls";    using (FileStream file = new FileStream(fileName, FileMode.Create))    {        hssfWorkbook.Write(file);        file.Close();    }需要注意的是,调色板的取值范围是0x8 - 0x40,即8-64,也就是说只支持56种颜色,56种颜色在项目中也差不多够用了。还有就是所调用的颜色一定要存在于调色板中否则在调用FindColor后会返回null,再调用HSSFColor的GetIndex方法时会报错。
最后发一张完整示例项目生成结果的截图, 各位同学如果感兴趣可以将示例下载下来看一下 :-)

  /*修改样式关键代码*/
                        ICellStyle style = workbook.CreateCellStyle();
                        style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;
                        style.FillPattern = FillPattern.SolidForeground;
style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;
/*修改指定单元格样式 如果要修改行样式则需要将row.Cells.Count循环出来,挨个设置!*/
row.Cells[5].CellStyle = style;
 
                    
                     
                    
                 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号