最近自己开发一个 体育场的 选座 其中里的座位设置很让我头疼 显示在表格里填写 颜色 还要有座位号 里面的北京颜色非常难取 自己找里很长时间 最后 明白了怎么回事 首先我们要明白 取表格里的背景颜色 实际去的是 前景颜色 所以会用到 cell.getCellStyle().getFillForegroundColorColor() 这个方法 这里还有几个 去颜色的方法 虽然不怎么清楚 这几个刚发干嘛的 反正我用这个是取到了。
ColorInfo bgColor = null;
if (cell.getCellStyle().getFillPattern() == CellStyle.SOLID_FOREGROUND) {
bgColor = excelColor2UOF(cell.getCellStyle().getFillForegroundColorColor());
String rgb = "#"+bgColor.toRGB();//获得颜色号码
}
//获得表格里的颜色
private static ColorInfo excelColor2UOF(Color color) {
if (color == null) {
return null;
}
ColorInfo ci = null;
if (color instanceof HSSFColor) {// .xls
HSSFColor hc = (HSSFColor) color;
short[] s = hc.getTriplet();// 一定是rgb
if (s != null) {
ci = ColorInfo.fromARGB(s[0], s[1], s[2]);
}
} else
if (color instanceof XSSFColor) {// .xlsx
XSSFColor xc = (XSSFColor) color;
byte[] bs = xc.getARgb();
if (bs != null) {// 一定是argb
ci = new ColorInfo(sixteen((int)bs[0]),sixteen((int)bs[1]),sixteen((int)bs[2]),sixteen((int)bs[3]));
}
}
return ci;
}
//传过来的是二进制 转换成十进制
private static int sixteen(int number){
return ((number & 0x0f0) >> 4)*16 +(number & 0x0f);
}
这里需要穿件一个 pojo类
package com.huayu.pw.util;
public class ColorInfo {
/**
* 颜色的alpha值,此值控制了颜色的透明度
*/
public int A;
/**
* 颜色的红分量值,Red
*/
public int R;
/**
* 颜色的绿分量值,Green
*/
public int G;
/**
* 颜色的蓝分量值,Blue
*/
public int B;
public ColorInfo() {
super();
}
public String toRGB() {
String r,g,b;
StringBuilder su = new StringBuilder();
r = Integer.toHexString(R);
g = Integer.toHexString(G);
b = Integer.toHexString(B);
r = r.length() == 1 ? "0" + r : r;
g = g.length() ==1 ? "0" +g : g;
b = b.length() == 1 ? "0" + b : b;
r = r.toUpperCase();
g = g.toUpperCase();
b = b.toUpperCase();
su.append(r);
su.append(g);
su.append(b);
return su.toString();
}
public java.awt.Color toAWTColor(){
return new java.awt.Color(this.R,this.G,this.B,this.A);
}
public static ColorInfo fromARGB(int red, int green, int blue) {
return new ColorInfo((int) 0xff, (int) red, (int) green, (int) blue);
}
public static ColorInfo fromARGB(int alpha, int red, int green, int blue) {
return new ColorInfo(alpha, red, green, blue);
}
public ColorInfo(int a,int r, int g , int b ) {
this.A = a;
this.B = b;
this.R = r;
this.G = g;
}
public int getA() {
return A;
}
public void setA(int a) {
A = a;
}
public int getR() {
return R;
}
public void setR(int r) {
R = r;
}
public int getG() {
return G;
}
public void setG(int g) {
G = g;
}
public int getB() {
return B;
}
public void setB(int b) {
B = b;
}
}
方法与类的名字 都弄成一个颜色的了 希望可以看懂
cell.getCellStyle().getFillForegroundColorColor();取出来的是一个对象 需要强转成HSSFColor
在这个对象里 会有对应的方法 xc.getARgb(); 取到对应的 argb值 但是取到的是 二进制的 所以要吧每个值转换成十进制 直接按照 int值转就可以 在上面我吧 代码已经放上了 等转完了 你拿到的 就是 真正的argb值了
当时我做的时候 只是测试 07版本的 xlsx
03版本的我没有测试