一个简单的测试用例,用来解析xlsx文件获取字体颜色
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;
public class testReadExcel {
public static void readExcel () throws Exception {
String path = "d:\\字体颜色1.xlsx";
File file = new File(path);
InputStream is = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(is);
int numbersheets = wb.getNumberOfSheets();
Sheet sheet = wb.getSheetAt(0);
int cols = sheet.getPhysicalNumberOfRows();
for(int i = 0; i<cols;i++) {
Row row = sheet.getRow(i);
int cellnumber = row.getPhysicalNumberOfCells();
for(int j = 0;j<cellnumber;j++) {
Cell cell = row.getCell(j);
CellStyle cellstyle1 = ((XSSFCell)cell).getCellStyle();
XSSFCellStyle cellstyle = (XSSFCellStyle)cellstyle1;
/*设置上边框大小和颜色边框*/
if(isHssf) {//这里的ishssf用来判断是否是hssf类型。
。。。
}else {
XSSFColor xsstopcolor = xsscellstyle.getTopBorderXSSFColor();
String gc = xssBorderColor(xsstopcolor);
if(!StrFunc.isNull(gc)) {
ecell.setBorderTopColor(gc);
}
}
/**
* 字体,关键是从cellstyle开始就要进行格式的转化,转成xssf的专有格式。
*/
XSSFFont font1 = cellstyle.getFont();
XSSFColor xsscolor = font1.getXSSFColor();
byte[] rgbcolor1 = xsscolor.getRGB();
String argbHex = xsscolor.getARGBHex();
byte[] rgbcolor = xsscolor.getARGB();
System.out.println("argb"+rgbcolor);
System.out.println("argbHex"+argbHex);
StringBuffer sb = new StringBuffer();
if (rgbcolor != null) {
sb.append("#");
for (int z = 0; z < rgbcolor.length; z++) {
String part = Integer.toHexString(rgbcolor[z]);
System.out.println(part);
sb.append(part);
}
}
System.out.println(sb);
}
}
}
public String xssBorderColor(XSSFColor xc) {
if(xc!=null) {
String argbcolor = xc.getARGBHex();
if(!StrFunc.isNull(argbcolor)) {
String gc = getColor(argbcolor);
return gc;
}
}
return null;
}
public String getColor(String str) {
StringBuffer sb = new StringBuffer();
sb.append("#");
if(str.length()>=8) {
str = str.substring(2, 8);
}
sb.append(str);
return sb.toString();
}
public static void main(String[] args) throws Exception{
readExcel();
}
}