apache poi를 사용한 셀 색상 변경
Apache POI를 사용하여 부품 번호 스프레드시트의 데이터를 읽고 있습니다.데이터베이스에서 부품 번호를 검색하여 부품의 CAD 도면이 있으면 부품 번호 셀을 녹색으로 칠하고, 빨간색으로 칠하지 않으면 빨간색으로 칠합니다.처리가 완료되면 스프레드시트가 저장됩니다.제가 안고 있는 문제는 그 열의 모든 셀이 녹색으로 나온다는 것입니다.코드를 확인해보니 부품 번호를 조회하는 논리는 정상적으로 작동하고 있으며 셀의 색상을 결정하고 색상과 채우기 설정을 하는 논리도 제대로 작동하는 것 같습니다.내가 여기서 뭘 잘못하고 있는지 알기나 해?
감사해요.
//Check the parts
for(int r=1;r<sheet.getPhysicalNumberOfRows();r++) {
String partNumber = null;
switch(cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
long pNum = (long) cell.getNumericCellValue();
partNumber = String.valueOf(pNum);
break;
case HSSFCell.CELL_TYPE_STRING:
partNumber = cell.getStringCellValue();
break;
default:
logger.info("Part Number at row " + r + " on sheet " + partList.getSheetName(s) + "is of an unsupported type");
}
try {
List<String> oldMaterialNumbers = getOldMaterialNumbers(partNumber);
boolean gotDrawing = checkPartNumber(oldMaterialNumbers, partNumber);
//If there's a drawing then color the row green, if not red.
short bgColorIndex = gotDrawing
?HSSFColor.LIGHT_GREEN.index //42
:HSSFColor.RED.index; //10
HSSFCell curCell = row.getCell(partNumberColumn);
HSSFCellStyle curStyle = curCell.getCellStyle();
curStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
curStyle.setFillForegroundColor(bgColorIndex);
curCell.setCellStyle(curStyle);
}catch(Exception e) {
throw e;
}
}
쇼트 버전:스타일을 한 번만 만들고 어디에서나 사용합니다.
Long version : 원하는 스타일을 작성하기 위한 방법을 사용합니다(스타일 수 제한에 주의).
private static Map<String, CellStyle> styles;
private static Map<String, CellStyle> createStyles(Workbook wb){
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
DataFormat df = wb.createDataFormat();
CellStyle style;
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short) 12);
style = createBorderedStyle(wb);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(headerFont);
styles.put("style1", style);
style = createBorderedStyle(wb);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFont(headerFont);
style.setDataFormat(df.getFormat("d-mmm"));
styles.put("date_style", style);
...
return styles;
}
스타일 해시맵을 만드는 동안 반복 작업을 수행하는 메서드를 사용할 수도 있습니다.
private static CellStyle createBorderedStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
return style;
}
그런 다음 "기본" 코드에서 스타일 맵에서 스타일을 설정합니다.
Cell cell = xssfCurrentRow.createCell( intCellPosition );
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );
셀 스타일을 작성하려면 http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors 를 참조하십시오.
커스텀 컬러
HSSF:
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");
//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background
HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);
cell.setCellStyle(style);
//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();
//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)
cell.setCellValue("Modified Palette");
//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
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);
//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();
XSSF:
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");
XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
style1.setFillPattern(CellStyle.SOLID_FOREGROUND);
그래서 그런 것 같아요cell.getCellStyle처음에 기본 셀 스타일을 반환한 후 변경할 수 있습니다.
다음과 같은 스타일을 만들어 셀에 적용합니다.
cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();
이전 포스터에서 언급한 것처럼 스타일을 만들고 재사용해 보십시오.
또한 XSSF 라이브러리에는 제공된 코드를 사용하지 않고 자동으로 스타일을 재사용하는 유틸리티 클래스도 있습니다.클래스 0FF 손이 기억나지 않습니다.
여기서 예제를 확인하다
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
Apache POI 3.9의 경우 아래 코드를 사용할 수 있습니다.
HSSFCellStyle style = workbook.createCellStyle()
style.setFillForegroundColor(HSSFColor.YELLOW.index)
style.setFillPattern((short) FillPatternType.SOLID_FOREGROUND.ordinal())
3.9 버전의 메서드는 short를 받아들이므로 입력에 유의해야 합니다.
언급URL : https://stackoverflow.com/questions/11529542/changing-cell-color-using-apache-poi
'programing' 카테고리의 다른 글
| SQL Server: 과거 1년간의 데이터만 취득 (0) | 2023.04.16 |
|---|---|
| Xcode를 사용하여 "No such module" 오류가 발생하지만 프레임워크가 있습니다. (0) | 2023.04.16 |
| iPhone 시뮬레이터에서 시간과 시간대를 변경하는 방법은? (0) | 2023.04.16 |
| WPF에서 창을 앞으로 가져옵니다. (0) | 2023.04.16 |
| 커스텀 할당 해제 및 ARC(객관-C) (0) | 2023.04.16 |