Skip to content

Commit

Permalink
Fin gestión de formato de fuentes
Browse files Browse the repository at this point in the history
Se da por concluido, por ahora, el código de gestión de formato de
fuentes para métricas e indicadores
Se aprecia mucho código repetido, debería optmizarse la clase
ExcelReportManager
  • Loading branch information
Isabel-Roman committed Mar 5, 2024
1 parent ba7607d commit eac27ad
Show file tree
Hide file tree
Showing 2 changed files with 156 additions and 104 deletions.
227 changes: 124 additions & 103 deletions src/main/java/us/muit/fs/a4i/persistence/ExcelReportManager.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
/**
*
*/
package us.muit.fs.a4i.persistence;

import java.io.FileInputStream;
Expand All @@ -16,15 +13,6 @@

import org.apache.poi.EncryptedDocumentException;

/**
* import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbookFactory;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
*/
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFFont;
Expand All @@ -34,8 +22,6 @@
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.model.StylesTable;



import us.muit.fs.a4i.exceptions.ReportNotDefinedException;
import us.muit.fs.a4i.model.entities.ReportI;
import us.muit.fs.a4i.model.entities.ReportItemI;
Expand Down Expand Up @@ -63,22 +49,25 @@
* Si la hoja exist�a la recupera y se añadirá sobre ella, no se elimina lo
* anterior, si no existía se crea nueva
* </p>
* <p>
* Deuda técnica. En la persistencia de métricas e indicadores se observa mucho código replicado, se debe optimizar
* </p>
*
* @author Isabel Román
*
*
*/
public class ExcelReportManager implements PersistenceManager, FileManager {
private static Logger log = Logger.getLogger(ExcelReportManager.class.getName());
private Map<String,XSSFCellStyle> styles=new HashMap<String,XSSFCellStyle>();

private Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();
/**
* <p>
* Referencia al gestor de estilo que se va a utilizar
* </p>
*/
protected ReportFormaterI formater;

FileInputStream inputStream = null;

/**
Expand Down Expand Up @@ -107,7 +96,6 @@ public ExcelReportManager() {
super();
}


@Override
public void setFormater(ReportFormaterI formater) {
log.info("Establece el formateador");
Expand Down Expand Up @@ -141,10 +129,10 @@ public void setName(String name) {
* @throws EncryptedDocumentException documento protegido
*/
protected XSSFSheet getCleanSheet(String entityId) throws EncryptedDocumentException, IOException {
log.info("Solicita una hoja nueva del libro manejado, para la entidad con id: "+entityId);
log.info("Solicita una hoja nueva del libro manejado, para la entidad con id: " + entityId);
if (wb == null) {
inputStream = new FileInputStream(filePath + fileName);

wb = new XSSFWorkbook(inputStream);
log.info("Generado workbook");

Expand Down Expand Up @@ -180,25 +168,23 @@ protected XSSFSheet getCleanSheet(String entityId) throws EncryptedDocumentExcep
}

/**
* Un informe será una hoja en el libro excel
* Guarda en un hoja limpia con el nombre del id del informe
* Incluye todas las métricas y los indicadores que tenga report
* Un informe será una hoja en el libro excel Guarda en un hoja limpia con el
* nombre del id del informe Incluye todas las métricas y los indicadores que
* tenga report
*/
@Override
public void saveReport(ReportI report){
log.info("Guardando informe con id: "+report.getEntityId());
public void saveReport(ReportI report) {
log.info("Guardando informe con id: " + report.getEntityId());
try {
FileOutputStream out;
if (sheet == null) {
sheet = getCleanSheet(report.getEntityId());
}

/**
* A partir de la última que haya
* Fila 1: Encabezado métricas
* Filas 2 a N:Para cada métrica del informe una fila
* Fila N+1: Encabezado indicadores
* Filas N+2 a M: Para cada indicador una fila
* A partir de la última que haya Fila 1: Encabezado métricas Filas 2 a N:Para
* cada métrica del informe una fila Fila N+1: Encabezado indicadores Filas N+2
* a M: Para cada indicador una fila
*/
int rowIndex = sheet.getLastRowNum();
rowIndex++;
Expand All @@ -210,20 +196,20 @@ public void saveReport(ReportI report){
persistMetric(metric);
rowIndex++;
}
//Ahora irían los indicadores
// Ahora irían los indicadores
rowIndex++;
sheet.createRow(rowIndex).createCell(0).setCellValue("Indicadores");
sheet.createRow(rowIndex).createCell(0).setCellValue("Indicadores");
collection = report.getAllIndicators();
for (ReportItemI indicator : collection) {
persistIndicator(indicator);
rowIndex++;
}
out = new FileOutputStream(filePath + "NEW"+fileName);

out = new FileOutputStream(filePath + "NEW" + fileName);
wb.write(out);
out.close();
} catch (Exception e) {

e.printStackTrace();
}
}
Expand All @@ -236,110 +222,145 @@ private void persistMetric(ReportItemI metric) {
XSSFRow row = sheet.createRow(rowIndex);
log.info("Indice de fila nueva " + rowIndex);
int cellIndex = 0;
// Aquí debería incorporar el formato de fuente en las celdas
// docs sacados de aquí https://www.javatpoint.com/apache-poi-excel-font
// https://www.e-iceblue.com/Tutorials/Java/Spire.XLS-for-Java/Program-Guide/Cells/Apply-Fonts-in-Excel-in-Java.html

//CellStyle style = wb.createCellStyle();
//style.setFont((Font) formater.getMetricFont());

row.createCell(cellIndex++).setCellValue(metric.getName());
row.createCell(cellIndex++).setCellValue(metric.getValue().toString());
row.createCell(cellIndex++).setCellValue(metric.getUnit());
row.createCell(cellIndex++).setCellValue(metric.getDescription());
row.createCell(cellIndex++).setCellValue(metric.getSource());
StylesTable stylesTable = wb.getStylesSource();
stylesTable.ensureThemesTable();
XSSFCellStyle style = styles.get("metricStyle");

if (style == null) {

style = stylesTable.createCellStyle();
XSSFFont poiFont = wb.createFont();

Font a4iFont = formater.getMetricFont();
// Establezco el color y la fuente a utilizar en el texto de los indicadores.
byte[] color = { (byte) a4iFont.getColor().getRed(), (byte) a4iFont.getColor().getGreen(),
(byte) a4iFont.getColor().getBlue() };
XSSFColor myColor = new XSSFColor(color);
log.info("El nuevo color es " + myColor.getARGBHex());

poiFont.setFontHeightInPoints((short) a4iFont.getFont().getSize());
poiFont.setFontName(a4iFont.getFont().getFamily());
poiFont.setColor(myColor);
poiFont.setBold(true);
poiFont.setItalic(false);

log.info("La nueva fuente poi es " + poiFont.toString());

// style.setFillBackgroundColor(a4iFont.getColor().toString());
style.setFont(poiFont);
style.setFillBackgroundColor(myColor);
styles.put("metricStyle", style);
log.info("Creado el estilo con indice " + style.getIndex());
}

XSSFCell cell;

cell=row.createCell(cellIndex);
cell.setCellValue(metric.getName());
cell.setCellStyle(style);
sheet.autoSizeColumn(cellIndex++);

cell=row.createCell(cellIndex);
cell.setCellValue(metric.getValue().toString());
cell.setCellStyle(style);
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(metric.getUnit());
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(metric.getDescription());
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(metric.getSource());
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(metric.getDate().toString());
log.info("Indice de celda final" + cellIndex);
sheet.autoSizeColumn(cellIndex);
log.info("Indice de celda final " + cellIndex);

}

private void persistIndicator(ReportItemI indicator) {

log.info("Introduzco indicador en la hoja");
//Mantengo uno diferente porque en el futuro la información del indicador será distinta a la de la métrica
// Mantengo uno diferente porque en el futuro la información del indicador será
// distinta a la de la métrica
int rowIndex = sheet.getLastRowNum();
rowIndex++;
XSSFRow row = sheet.createRow(rowIndex);
log.info("Indice de fila nueva " + rowIndex);
int cellIndex = 0;
StylesTable stylesTable=wb.getStylesSource();
int cellIndex = 0;
StylesTable stylesTable = wb.getStylesSource();
stylesTable.ensureThemesTable();



XSSFCellStyle style=styles.get(indicator.getIndicator().getState().toString());
XSSFCellStyle style = styles.get(indicator.getIndicator().getState().toString());
try {
if (style==null){
if (style == null) {

style = stylesTable.createCellStyle();
XSSFFont poiFont = wb.createFont();

Font a4iFont=formater.getIndicatorFont(indicator.getIndicator().getState());
//Establezco el color y la fuente a utilizar en el texto de los indicadores.

// HSSFPalette palette = wb.getCustomPalette();
// get the color which most closely matches the color you want to use
//HSSFColor myColor = palette.findSimilarColor(a4iFont.getColor().getRed(), a4iFont.getColor().getGreen(), a4iFont.getColor().getBlue());
// get the palette index of that color
//HSSFColor myColor=new HSSFColor(0,0,a4iFont.getColor());
byte[] color= {(byte) a4iFont.getColor().getRed(),(byte) a4iFont.getColor().getGreen(),(byte) a4iFont.getColor().getBlue()};
XSSFColor myColor=new XSSFColor(color);

log.info("El nuevo color es "+myColor.getARGBHex());


//myColor.setIndexed(newColor++);

poiFont.setFontHeightInPoints((short)a4iFont.getFont().getSize());
XSSFFont poiFont = wb.createFont();

Font a4iFont = formater.getIndicatorFont(indicator.getIndicator().getState());
// Establezco el color y la fuente a utilizar en el texto de los indicadores.
byte[] color = { (byte) a4iFont.getColor().getRed(), (byte) a4iFont.getColor().getGreen(),
(byte) a4iFont.getColor().getBlue() };
XSSFColor myColor = new XSSFColor(color);

log.info("El nuevo color es " + myColor.getARGBHex());

// myColor.setIndexed(newColor++);

poiFont.setFontHeightInPoints((short) a4iFont.getFont().getSize());
poiFont.setFontName(a4iFont.getFont().getFamily());
poiFont.setColor(myColor);
poiFont.setColor(myColor);
poiFont.setBold(true);
poiFont.setItalic(false);
log.info("La nueva fuente poi es "+poiFont.toString());
//style.setFillBackgroundColor(a4iFont.getColor().toString());
poiFont.setItalic(false);

log.info("La nueva fuente poi es " + poiFont.toString());

// style.setFillBackgroundColor(a4iFont.getColor().toString());
style.setFont(poiFont);
style.setFillBackgroundColor(myColor);

styles.put(indicator.getIndicator().getState().toString(), style);
log.info("Creado el estilo con indice "+style.getIndex());

log.info("Creado el estilo con indice " + style.getIndex());
}
XSSFCell cell;

row.createCell(cellIndex).setCellValue(indicator.getName());
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(indicator.getValue().toString());

cell=row.createCell(cellIndex);
cell.setCellValue(indicator.getName());
cell.setCellStyle(style);
sheet.autoSizeColumn(cellIndex++);

cell=row.createCell(cellIndex);
cell.setCellValue(indicator.getValue().toString());
cell.setCellStyle(style);
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(indicator.getUnit());
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(indicator.getDescription());
sheet.autoSizeColumn(cellIndex++);
cell=row.createCell(cellIndex);
cell.setCellStyle(style);
log.info("Establecido el estilo con indice "+style.getIndex()+" en la celda "+cellIndex);

cell = row.createCell(cellIndex);
cell.setCellStyle(style);
log.info("Establecido el estilo con indice " + style.getIndex() + " en la celda " + cellIndex);
cell.setCellValue(indicator.getIndicator().getState().toString());
sheet.autoSizeColumn(cellIndex++);
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(indicator.getSource());
sheet.autoSizeColumn(cellIndex++);
sheet.autoSizeColumn(cellIndex++);

row.createCell(cellIndex).setCellValue(indicator.getDate().toString());
sheet.autoSizeColumn(cellIndex);
log.info("Indice de celda final " + cellIndex);
log.info("Indice de celda final " + cellIndex);

} catch (IOException e) {
log.warning("Problema al abrir el fichero con los formatos");
e.printStackTrace();
}



}

@Override
Expand Down
Loading

0 comments on commit eac27ad

Please sign in to comment.