-
Notifications
You must be signed in to change notification settings - Fork 66
B 读取单元格样式
guanquan.wang edited this page Aug 12, 2025
·
2 revisions
EEC从v0.5.6开始支持读取单元格样式,Row对象提供getCellStyle方法获取单元格样式,此样式仅返回一个int值表示样式索引,如果要获得具体的样式,
你需要从Styles对象中调用具体的getFont,getFill,getNumFmt,getBorder,getVertical,getHorizontal来分别获取 字体,填充,格式化,边框,垂直对齐,水平对齐 6个样式
// 第一步 获取Styles对象
Styles styles = row.getStyles();
// 第二步 获取指定单元格样式
int style = row.getCellStyle(cell);
// 获取字体
Font font = styles.getFont(style);
// 获取边框
Border border = styles.getBorder(style);
// 获取填充
Fill fill = styles.getFill(style);
// 获取格式化
NumFmt fmt = styles.getNumFmt(style);
// 水平对齐
String horizontal = Horizontals.of(styles.getHorizontal(style));
// 垂直对齐
String vertical = Verticals.of(styles.getVertical(style));通过上面的方法你可以完整的复制一个excel
读取所有单元格的样式保存到Map中,Key保存单元格位置信息如A1, B10,Value值为样式对象StyleEntry
/**
* 聚合样式对象
*/
public class StyleEntry {
public Font font;
public Fill fill;
public Border border;
public NumFmt numFmt;
public int verticals;
public int horizontals;
public boolean wrapText;
}
/**
* 读取所有单元格样式,并返回Map对象
*
* @param excelPath excel路径
* @return Key:单元格的位置信息{@code A1,B10},Value:StyleEntry包含所有样式
* @throws IOException 读取Excel异常
*/
public static Map<String, StyleEntry> getAllCellStyles(Path excelPath) throws IOException {
Map<String, StyleEntry> styleMap = new HashMap<>();
try (ExcelReader reader = ExcelReader.read(excelPath)) {
Styles styles = reader.getStyles();
for (Iterator<Row> iter = reader.sheet(0).iterator(); iter.hasNext(); ) {
Row row = iter.next();
// 遍历所有单元格并读取样式并转为StyleEntry对象
for (int i = row.fc; i < row.lc; i++) {
String rc = toCoordinate(row.getRowNum(), i + 1);
int xf = row.getCellStyle(i);
StyleEntry se = new StyleEntry();
se.font = styles.getFont(xf);
se.fill = styles.getFill(xf);
se.border = styles.getBorder(xf);
se.numFmt = styles.getNumFmt(xf);
se.verticals = styles.getVertical(xf);
se.horizontals = styles.getHorizontal(xf);
se.wrapText = styles.getWrapText(xf) == 1;
styleMap.put(rc, se);
}
}
}
return styleMap;
}让JAVA操作excel更简单