Excel转PDF:如何将Apache POI中getBottomBorderColor()返回值转为RGB?
嘿,我之前刚好遇到一模一样的需求!用Apache POI读Excel、iText生成PDF,一开始全是默认的黑色边框,完全还原不了Excel里的样式。下面就给你讲清楚怎么把POI返回的short类型边框色值转成iText能用的RGB颜色,完美复刻原表的边框:
解决步骤:从POI边框色到iText RGB颜色
1. 先搞懂POI的颜色值逻辑
POI里CellStyle.getBottomBorderColor()返回的short值分两种场景:
- 对于
.xls格式(HSSF):这个short是颜色索引,对应Excel内置调色板的位置 - 对于
.xlsx格式(XSSF):如果是自定义颜色,优先通过getBottomBorderXSSFColor()直接获取颜色对象;如果是内置索引色,再用索引值查找
2. 编写通用颜色转换工具方法
我写了一个兼容HSSF和XSSF的转换方法,直接就能用:
import org.apache.poi.hssf.usermodel.HSSFColor; import org.apache.poi.hssf.usermodel.HSSFPalette; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.itextpdf.kernel.colors.BaseColor; public static BaseColor convertPOIBorderColorToITextColor(CellStyle cellStyle, Workbook workbook) { short borderColorIndex = cellStyle.getBottomBorderColor(); // 处理旧版xls(HSSF)格式 if (workbook instanceof HSSFWorkbook) { HSSFPalette palette = ((HSSFWorkbook) workbook).getCustomPalette(); HSSFColor hssfColor = palette.getColor(borderColorIndex); if (hssfColor != null) { return new BaseColor(hssfColor.getRed(), hssfColor.getGreen(), hssfColor.getBlue()); } } // 处理新版xlsx(XSSF)格式 else if (workbook instanceof XSSFWorkbook) { XSSFCellStyle xssfCellStyle = (XSSFCellStyle) cellStyle; XSSFColor xssfColor = xssfCellStyle.getBottomBorderXSSFColor(); // 优先获取自定义颜色对象(更准确) if (xssfColor != null) { byte[] rgbBytes = xssfColor.getRGB(); // byte是有符号类型,转成0-255的无符号范围 return new BaseColor(rgbBytes[0] & 0xFF, rgbBytes[1] & 0xFF, rgbBytes[2] & 0xFF); } // 处理内置索引色的情况 XSSFColor indexedColor = ((XSSFWorkbook) workbook).getStylesSource().getIndexedColors().getColor(borderColorIndex); if (indexedColor != null) { byte[] rgbBytes = indexedColor.getRGB(); return new BaseColor(rgbBytes[0] & 0xFF, rgbBytes[1] & 0xFF, rgbBytes[2] & 0xFF); } } // 兜底:获取不到颜色时返回默认黑色,和原默认行为一致 return BaseColor.BLACK; }
3. 在iText中应用边框颜色
拿到转换后的BaseColor后,就可以给PDF单元格设置对应边框了。以iText 7为例,设置底部边框的代码如下(其他边框如top/left/right同理):
// 假设你已经获取了POI的Cell和对应的CellStyle CellStyle poiCellStyle = poiCell.getCellStyle(); BaseColor borderColor = convertPOIBorderColorToITextColor(poiCellStyle, workbook); // 创建iText的单元格对象(或复用你已有的Cell) com.itextpdf.layout.element.Cell itextCell = new com.itextpdf.layout.element.Cell(); // 同步边框颜色和宽度(宽度也从POI获取,还原度更高) itextCell.setBorderBottom(new com.itextpdf.layout.border.SolidBorder(borderColor, poiCellStyle.getBottomBorderWidth()));
小提示
- 一定要处理
null情况:如果POI返回的颜色对象为空,直接用默认黑色,避免空指针异常 - XSSF格式下优先用
getBottomBorderXSSFColor(),比索引值更适配自定义颜色 - 别忘了同步边框宽度!POI的
getBottomBorderWidth()可以直接拿到原Excel的边框粗细,一起应用到iText里更还原
内容的提问来源于stack exchange,提问作者Atul Patel
相关产品推荐
相关产品推荐

