Get Cell Colour with Apache POI

吃可爱长大的小学妹 提交于 2020-01-07 02:51:12

问题


I'm trying to learn how to use Apache POI with a small project. I want to use Excel to create 'room layouts' by using colour-coded cells, and load the data into a Java program. I think understand how to access the colour properties of a cell, but what I'm asking is:

Is it possible to access the colour of a blank cell (no data or value), or does a cell need to have data in order for Apache POI to read it?

I am only interested in the colour, so might it be preferable to put junk data in the cells, or possibly iterate through them based on coordinates? I'm brand new to Apache POI, so any help is greatly appreciated.


回答1:


What have you tried? Please read Busy Developers' Guide to HSSF and XSSF Features.

Supposing following Workbook:

Then the following code should work as well with a.xls (HSSF) as with a.xlsx (XSSF).

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import java.io.*;

class ReadExcelEmptyColoredCells {

 public static void main(String[] args) {
  try {

   //Workbook workbook = WorkbookFactory.create(new File("a.xls"));
   Workbook workbook = WorkbookFactory.create(new File("a.xlsx"));

   Sheet sheet = workbook.getSheetAt(0);

   for (Row row : sheet) {
    for (Cell cell : row) {
     if (! "".equals(String.valueOf(cell)))
      System.out.println(cell.getAddress() + ": " + String.valueOf(cell));
     CellStyle cellStyle = cell.getCellStyle();
     Color color = cellStyle.getFillForegroundColorColor();
     if (color != null) {
      if (color instanceof XSSFColor) {
       System.out.println(cell.getAddress() + ": " + ((XSSFColor)color).getARGBHex());
      } else if (color instanceof HSSFColor) {
       if (! (color instanceof HSSFColor.AUTOMATIC))
        System.out.println(cell.getAddress() + ": " + ((HSSFColor)color).getHexString());
      }
     }
    }
   }

   workbook.close();

  } catch (InvalidFormatException ifex) {
  } catch (FileNotFoundException fnfex) {
  } catch (IOException ioex) {
  }
 }
}


来源:https://stackoverflow.com/questions/39667614/get-cell-colour-with-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!