由于我是 NPOI 新手,我想向 Excel 工作表中的单元格添加颜色。我有一个像“#ffeeff”这样的十六进制值,并且ICellStyle.FillForegroundColor只能分配短整型值。
System.OverflowException:对于 Int16 来说值太大或太小。
我已经尝试过这样的代码并且它正在工作
style.FillForegroundColor = HSSFColor.Grey25Percent.Index;
Run Code Online (Sandbox Code Playgroud)
但我只有可以转换为 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)
Run Code Online (Sandbox Code Playgroud)
它不应该抛出错误,并且在 Excel 工作表中,必须将相同的颜色(fontcolorCode)应用于单元格
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
Run Code Online (Sandbox Code Playgroud)
您必须创建一个颜色对象:
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1607 次 |
| 最近记录: |