有没有办法在我的Excel文档中使用NPOI从十六进制值中添加颜色,如'#72fe9c'

问题描述 投票:1回答:1

因为我是NPOI的新手,我想在Excel工作表的单元格中添加颜色。我有一个像'#ffeeff'这样的十六进制值,在ICellStyle.FillForegroundColor中只能指定短整数值。

System.OverflowException:对于Int16,值太大或太小。

我尝试过像这样的代码,它正在运行

style.FillForegroundColor = HSSFColor.Grey25Percent.Index;

但我只有可以转换为int的十六进制值,但它只支持short int值。

//it is working
style.FillForegroundColor = HSSFColor.Grey25Percent.Index;

// not working for me as '#ffeeff' canot be converted to short, it can only be converted to int
style.FillForegroundColor = short.Parse(fontcolorCode.Substring(1), NumberStyles.HexNumber)

style.FillForegroundColor = short.Parse(fontcolorCode.Substring(1), NumberStyles.HexNumber) 

它不应该抛出错误,并且在excel表中,必须将相同的颜色(fontcolorCode)应用于单元格

c# excel npoi
1个回答
1
投票

shortInt16)对于这个值来说还不够大。取代intInt32):

string myHexColor = "#ffeeff";

int x = int.Parse(myHexColor.Substring(1), NumberStyles.HexNumber);

Console.WriteLine("Color is:  " + x);              //   16772863 
Console.WriteLine("Max short: " + short.MaxValue); //      32767
Console.WriteLine("Max int:   " + int.MaxValue);   // 2147483647

您必须创建一个Color对象:

string myHexColor = "#ffeeff";

byte r = Convert.ToByte(myHexColor.Substring(1, 2).ToUpper(), 16);
byte g = Convert.ToByte(myHexColor.Substring(3, 2), 16);
byte b = Convert.ToByte(myHexColor.Substring(5, 2), 16);
Console.WriteLine("{0} = {1}/{2}/{3}", myHexColor, r, g, b);

IWorkbook workbook = null;
NPOI.XSSF.UserModel.XSSFCellStyle style = (NPOI.XSSF.UserModel.XSSFCellStyle)workbook.CreateCellStyle();

// Here we create a color from RGB-values
IColor color = new NPOI.XSSF.UserModel.XSSFColor(new byte[] { r, g, b });

style.SetFillForegroundColor(color );

ICell cellToPaint = null; // Select your cell..
cellToPaint.CellStyle = style;
© www.soinside.com 2019 - 2024. All rights reserved.