600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 【转】NPOI自定义单元格背景颜色

【转】NPOI自定义单元格背景颜色

时间:2022-02-20 13:46:14

相关推荐

【转】NPOI自定义单元格背景颜色

经常在NPOI群里聊天时发现有人在问NPOI设置单元格背景颜色的问题,而Tony Qu大神的博客里没有相关教程,刚好最近在做项目时研究了一下这一块,在这里总结一下。

在NPOI中默认的颜色类是HSSFColor,如果要使用NPOI中的颜色就必须想办法转化为HSSFColor。分析了一下原代码,HSSFColor内置了几十种颜色,都是用内部类继承HSSFColor这个类来定义的。那么除非去修改源代码,否则是不能以这种方式来使用自定义颜色的。

除了继承的方式外,还有另外一种方式使用HSSFColor。答案就是从调色板中获取颜色。从调色板中获取颜色的主要步骤是:1、将颜色的RGB值添加进调色板HSSFPalette中。2、调用HSSFPalette中FindColor方法获取HSSFColor实例。3、在需要使用颜色的地方使用HSSFColor的GetIndex方法获取index值。以下是实现相关源代码:

intStartColIndex = 0;introwIndex = 0;intcolIndex = StartColIndex;HSSFWorkbook hssfWorkbook =newHSSFWorkbook();ISheet sheet = hssfWorkbook.CreateSheet("Sheet1");IRow row;ICell cell;HSSFPalette palette = hssfWorkbook.GetCustomPalette();List<Color> colorList =newList<Color>();Random random =newRandom(Guid.NewGuid().GetHashCode());for(inti = 0; i < random.Next(100, 200); i++){colorList.Add(Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)));}shortFIRST_COLOR_INDEX = (short)0x8;for(inti = 0; i < colorList.Count; i++){if((short)(FIRST_COLOR_INDEX + i) > (short)0x40){break;}//index的取值范围 0x8 - 0x40palette.SetColorAtIndex((short)(FIRST_COLOR_INDEX + i), colorList[i].R, colorList[i].G, colorList[i].B);}for(inti = 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;varv1 = palette.FindColor(colorList[i].R, colorList[i].G, colorList[i].B);if(v1 ==null){thrownewException("Color is not in Palette");}colorStyle.FillForegroundColor = v1.GetIndex();cell.CellStyle = colorStyle;colIndex++;rowIndex++;}stringfileName =@"test.xls";using(FileStream file =newFileStream(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;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。