2009-09-30 9 views
9

Mam istniejący arkusz kalkulacyjny programu Excel, do którego uzyskuję dostęp i odczytywam wartości z, używam Apache POI HSSF.Jak uzyskać kolor tła (Java Apache POI HSSF) dla danej komórki?

Jest zainicjowane tak:

HSSFSheet sheet; 
FileInputStream fis = new FileInputStream(this.file); 
POIFSFileSystem fs = new POIFSFileSystem(fis); 
HSSFWorkbook wb = new HSSFWorkbook(fs); 
this.sheet = wb.getSheet(exsheet); 

ja iteracji po wszystkich komórek, które istnieją w arkuszu, co czyni obiekt komórkowy:

HSSFCell cell = (HSSFCell) cells.next(); 

proszę może ktoś zaznajomiony z ram wyjaśnij, jak utworzyć obiekt (HSSFColor), aby odwzorować kolor tła każdej komórki w arkuszu.

Dziękujemy

EDIT, zaktualizuj

Żeby było jasne, co chcę wiedzieć, to: w jaki sposób mogę utworzyć/uzyskać HSSFColor obiekt dla koloru tła istniejącej komórce?

cell.getCellStyle().getFillBackgroundColor(); 

Ten kod zwraca tylko krótki numer, a nie obiekt HSSFColor. Dzięki za odpowiedzi do tej pory.

+0

(lub cell.getCellStyle) .getFillForegroundColor(), arkusz programu Excel, który odczytuję, zwraca ten sam kolor dla koloru tła, nawet jeśli komórka jest kolorowa. –

Odpowiedz

1

Można by zrobić coś takiego:

HSSFCell myCell = ...; 
HSSFCellStyle myStyle = workbook.createCellStyle(); 
myStyle.setFillBackgroundColor(HSSFColor.BLUE); 

myCell.setCellStyle(myStyle); 

Wierzę, że istnieje ograniczona liczba stylów dla danego skoroszytu; będziesz chciał ponownie użyć tego samego obiektu stylu, jeśli to możliwe.

[Edytuj: Przepraszam, to byłby kolor w komórce. Aby uzyskać kolor, należy jak:

myCell.getCellStyle().getFillBackgroundColor(); 

]

[Edit 2: Patrząc na informacje niestandardowych kolorów Craig pisał, może można spróbować:

HSSFColor.getIndexHash().get(myCell.getCellStyle().getFillBackgroundColor()) 

]

+0

Dzięki za dotychczasową odpowiedź, niestety nie jest to całkiem rozwiązanie, ponownie wyjaśniłem to pytanie. – java

+0

Zaktualizowałem moją odpowiedź z niewielką pomocą ze strony posta Craiga – RMorrisey

5

Aby uzyskać kolor: Krótka wartość zwracana przez getFillBackgroundColor jest indeksem Excel koloru. Możesz uzyskać kolor odpowiadający indeksowi w HashTable HSSFColor, używając ostatniego wskazanego kodu RMorrisey.

Aby ustawić kolor: Tworzysz niestandardową paletę i zmienisz kolor w danym indeksie. Następnie zastosujesz kolor do stylu.

//creating a custom palette for the workbook 
HSSFPalette palette = wb.getCustomPalette(); 
//replacing the standard red with freebsd.org red 
palette.setColorAtIndex(HSSFColor.RED.index, 
     (byte) 153, //RGB red (0-255) 
     (byte) 0, //RGB green 
     (byte) 0  //RGB blue 
); 
// or creating a new Color 
HSSFColor myColor = palette.addColor((byte) 153, (byte) 0, (byte) 0); 
HSSFCellStyle style = wb.createCellStyle(); 

style.setFillForegroundColor(myColor); 

Pozdrowienia

Guillaume informacje

2

backgroundColor z XSSFCellStyle można uzyskać z metody:

XSSFCellStyle.getFillForegroundXSSFColor().getCTColor() 

Można go wydrukować i widać to struktura.

0
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.Iterator;  
import org.apache.poi.hssf.usermodel.HSSFPalette;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.hssf.util.HSSFColor;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.CellStyle;  
import org.apache.poi.ss.usermodel.Row;  

/** 
* @author [email protected] 
* 
*/ 

public class ExcelPractice { 

    /** 
    * Must Read :  
    * 
    * Code to get the background color from an excel sheet in RGB Format and display on the console  
    * Save the content of the xls file into another OUTPUT.xls file.  
    * Using a sample sheet with only first row filled with background color.  
    * Code uses HSSF which means i am only using xls format.  
    * Using poi-3.5-FINAL.jar  
    * Solution with the output provided  
    * Observation : Some Custom color's are not recognized as they may not be defined  
    * in the excel color palette thus the code returns the almost similar color code.  
    */ 
    public static void main(String[] args) { 
     try { 
      FileInputStream fileInputStream=new FileInputStream(new  File("D:\\Excel_File.xls")); 

      HSSFWorkbook workbook=new HSSFWorkbook(fileInputStream); 
      HSSFSheet sheet=workbook.getSheetAt(0); 
      Iterator<Row> rowIterator= sheet.iterator(); 
      while (rowIterator.hasNext()) { 
       Row row=rowIterator.next(); 

       Iterator<Cell> cellIterator=row.cellIterator(); 
       while (cellIterator.hasNext()) { 
        Cell cell = (Cell) cellIterator.next(); 

         switch (cell.getCellType()) { 
         case Cell.CELL_TYPE_BOOLEAN: 
          System.out.println(cell.getBooleanCellValue()+"\t\t"); 
         System.out.println(cell.getCellStyle().getFillForegroundColor()); 
         break; 
        case Cell.CELL_TYPE_NUMERIC: 
         System.out.println(cell.getNumericCellValue()+"\t\t"); 
         System.out.println(cell.getCellStyle().getFillForegroundColor()); 
         break; 
        case Cell.CELL_TYPE_STRING: 
         System.out.println(cell.getStringCellValue()+"\t\t"); 
         //System.out.println(HSSFColor.getIndexHash().get(cell.getCellStyle().getFillBackgroundColor())); 
         int num=cell.getColumnIndex(); 
         Cell cell1 = row.getCell(num); 
         CellStyle cellStyle = cell1.getCellStyle();   
         getColorPattern(cellStyle.getFillForegroundColor()); 
         break; 
        default: 
         break; 
        } 
       } 
       System.out.println(); 

       fileInputStream.close(); 
       FileOutputStream fileOutputStream=new FileOutputStream(new File("D:\\OUTPUT.xls")); 
       workbook.write(fileOutputStream); 
       fileInputStream.close(); 
      } 


    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.toString(); 
    } 
    catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

//Method to identify the color pattern 
private static short[] getColorPattern(short colorIdx){   
    short[] triplet = null; 
    HSSFWorkbook workbook=new HSSFWorkbook(); 
    HSSFPalette palette = workbook.getCustomPalette(); 
    HSSFColor color = palette.getColor(colorIdx); 
    triplet = color.getTriplet();  
    System.out.println("color : " + triplet[0] +"," + triplet[1] + "," +  triplet[2]); 
    return triplet; 
} 
} 

/** Output of the above code as executed in my system 
S.NO.  
color : 255,255,0 
VTU Number  
color : 0,128,0 
First Name  
color : 51,204,204 
Middle Name  
color : 255,0,0 
Last Name  
color : 102,102,153 
Branch  
color : 255,102,0 
E-mail id  
color : 0,255,0 
Mobile Number  
color : 255,255,255 
*/ 

Screen shot from the Excel_File.xls file

1

Aby uzyskać kolor tła konkretnej komórki w HEX, użyj tego:

cell.getCellStyle().getFillForegroundColorColor().getARGBHex() 

Wskazówka słowo Color służy dwukrotnie

0

Poniżej dla XSSF i jest w Scala, ale pokazuje dokładnie, jak uzyskać kolor z modelu obiektu. Chciałem utworzyć instancję java.awt.Color z rzeczywistych wartości rgb (co jest przydatne częściowo dlatego, że mój debugger wyświetla dla mnie rzeczywisty kolor obiektu, gdy zatrzymuję się w punktach przerwania, a częściowo dlatego, że jest przeznaczony do eksportu do systemów, które mają nic wspólnego z Excelem). Ignoruję wartość alfa koloru, a moja Scala może być nieco naiwna. Sugeruję, że jeśli ten nie działa, należy ustawić punkt przerwania i zbadać wynik metody ściśle związane wywołuje takie jak getFill Powrót groundColorColor()

val rgb: Array[Byte] = cell.getCellStyle.getFillForegroundColorColor.getRgb 
    def toInt(b: Byte): Int = { 
     if (b<0) 256+b else b 
    } 
    val rgbInts = rgb.map(toInt) 
    val color = new Color(rgbInts(0),rgbInts(1),rgbInts(2)) 
Powiązane problemy