要解决这个问题,可以使用Apache POI的getFillForegroundColorColor()
和getFillBackgroundColorColor()
方法来获取单元格的前景色和背景色。
下面是一个示例代码,演示如何使用Apache POI来获取单元格的前景色和背景色:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class CellColorExample {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("path/to/your/excel/file.xlsx");
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
// 获取前景色
CellStyle cellStyle = cell.getCellStyle();
Color foregroundColor = cellStyle.getFillForegroundColorColor();
System.out.println("Foreground color: " + foregroundColor);
// 获取背景色
Color backgroundColor = cellStyle.getFillBackgroundColorColor();
System.out.println("Background color: " + backgroundColor);
file.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请将代码中的path/to/your/excel/file.xlsx
替换为你的实际Excel文件的路径。
通过使用getFillForegroundColorColor()
和getFillBackgroundColorColor()
方法,你可以获取单元格的前景色和背景色。如果单元格的前景色和背景色不同,返回的颜色对象将反映这些差异。如果单元格的前景色和背景色相同,返回的颜色对象将是相同的。