texto setcolumnwidth poi formato example desde dar combinar color celdas celda cambiar ajustar java excel apache-poi

setcolumnwidth - dar formato a celdas de excel desde java



Cambiando el color de la celda usando apache poi. (5)

Creo que es porque cell.getCellStyle inicialmente devuelve el estilo de celda predeterminado que luego cambia.

Crea estilos como este y aplícalos a las celdas:

cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();

Aunque como el cartel anterior señaló, intente crear estilos y reutilizarlos.

También hay alguna clase de utilidad en la biblioteca XSSF que evitará el código que proporcioné e intentará y reutilizará automáticamente los estilos. No recuerdo la mano de la clase 0ff.

Estoy usando Apache POI para leer datos en una hoja de cálculo de números de pieza. Busco el número de parte en nuestra base de datos, si tenemos un dibujo en CAD de la parte colorearé la celda de número de parte verde, si no lo hacemos, lo pintaremos de rojo. Una vez finalizado el proceso, se guarda la hoja de cálculo. El problema que tengo es que cada celda de esa columna sale verde. He revisado el código, la lógica para buscar el número de pieza está funcionando bien y la lógica para determinar de qué color debe ser la celda y configurar el color y el relleno parece funcionar también. ¿Alguna idea de lo que estoy haciendo mal aquí?

Gracias.

//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; } }


Para apache POI 3.9 puede usar el siguiente código:

HSSFCellStyle style = workbook.createCellStyle() style.setFillForegroundColor(HSSFColor.YELLOW.index) style.setFillPattern((short) FillPatternType.SOLID_FOREGROUND.ordinal())

Los métodos para la versión 3.9 aceptan en corto y debe prestar atención a las entradas.


Para crear sus estilos de celda, consulte: http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors .

Colores personalizados

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);


Versión corta: crea estilos solo una vez, úsalos en todas partes.

Versión larga: use un método para crear los estilos que necesita (tenga cuidado con el límite en la cantidad de estilos).

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; }

También puede utilizar métodos para realizar tareas repetitivas mientras crea estilos hashmap.

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; }

luego, en su código "principal", configure el estilo del mapa de estilos que tiene.

Cell cell = xssfCurrentRow.createCell( intCellPosition ); cell.setCellValue( blah ); cell.setCellStyle( (CellStyle) styles.get("style1") );