Есть ли способ добавить цвет в ячейку из шестнадцатеричного значения, как '# 72fe9c' в моем документе Excel, используя NPOI - PullRequest
1 голос
/ 04 апреля 2019

Поскольку я новичок в NPOI и хочу добавить цвет к ячейке в моем листе Excel.У меня есть шестнадцатеричное значение, подобное «#ffeeff», и в ICellStyle.FillForegroundColor может быть назначено только короткое значение типа int.

System.OverflowException: значение было слишком большим или слишком маленьким для Int16.

Я пробовал подобный код, и он работает

style.FillForegroundColor = HSSFColor.Grey25Percent.Index;

, но у меня есть только шестнадцатеричное значение, которое можно преобразовать в int, но оно поддерживает только короткие значения 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)

1 Ответ

1 голос
/ 04 апреля 2019

short (Int16) недостаточно велико для этого значения.Взять вместо этого int (Int32):

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;
...