List of usage examples for org.apache.poi.ss.usermodel Cell setCellValue
void setCellValue(boolean value);
From source file:apm.common.utils.excel.ExportExcel.java
License:Open Source License
/** * ?/* ww w. j av a 2s. co m*/ * @param title ? * @param headerList */ private void initialize(String title, List<String> headerList) { this.wb = new SXSSFWorkbook(500); this.sheet = wb.createSheet("Export"); this.styles = createStyles(wb); // Create title if (StringUtils.isNotBlank(title)) { Row titleRow = sheet.createRow(rownum++); titleRow.setHeightInPoints(30); Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), headerList.size() - 1)); } // Create header if (headerList == null) { throw new RuntimeException("headerList not null!"); } Row headerRow = sheet.createRow(rownum++); headerRow.setHeightInPoints(16); for (int i = 0; i < headerList.size(); i++) { Cell cell = headerRow.createCell(i); cell.setCellStyle(styles.get("header")); String[] ss = StringUtils.split(headerList.get(i), "**", 2); if (ss.length == 2) { cell.setCellValue(ss[0]); Comment comment = this.sheet.createDrawingPatriarch() .createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6)); comment.setString(new XSSFRichTextString(ss[1])); cell.setCellComment(comment); } else { cell.setCellValue(headerList.get(i)); } sheet.autoSizeColumn(i); } for (int i = 0; i < headerList.size(); i++) { int colWidth = sheet.getColumnWidth(i) * 2; sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth); } log.debug("Initialize success."); }
From source file:apm.common.utils.excel.ExportExcel.java
License:Open Source License
/** * ?//w w w.j a va 2 s. c o m * @param row * @param column ? * @param val * @param align ??1?23?? * @return ? */ public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType) { Cell cell = row.createCell(column); CellStyle style = styles.get("data" + (align >= 1 && align <= 3 ? align : "")); try { if (val == null) { cell.setCellValue(""); } else if (val instanceof String) { cell.setCellValue((String) val); } else if (val instanceof Integer) { cell.setCellValue((Integer) val); } else if (val instanceof Long) { cell.setCellValue((Long) val); } else if (val instanceof Double) { cell.setCellValue((Double) val); } else if (val instanceof Float) { cell.setCellValue((Float) val); } else if (val instanceof Date) { DataFormat format = wb.createDataFormat(); style.setDataFormat(format.getFormat("yyyy-MM-dd")); cell.setCellValue((Date) val); } else { if (fieldType != Class.class) { cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val)); } else { cell.setCellValue((String) Class .forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), "fieldtype." + val.getClass().getSimpleName() + "Type")) .getMethod("setValue", Object.class).invoke(null, val)); } } } catch (Exception ex) { log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString()); cell.setCellValue(val.toString()); } cell.setCellStyle(style); return cell; }
From source file:appform.Complaint.java
public static void updateComplaint(String complaint) { try {/*from w w w. j av a 2 s.c o m*/ FileInputStream file = new FileInputStream(new File("Complaint.xls")); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); HashMap data; data = new HashMap<>(); data.put("7", new Object[] { complaint }); Set keyset = data.keySet(); int rownum = sheet.getLastRowNum() + 1; for (Object key : keyset) { Row row = sheet.createRow(rownum++); Object[] objArr = (Object[]) data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String) obj); else if (obj instanceof Double) cell.setCellValue((Double) obj); } } FileOutputStream out = new FileOutputStream(new File("Complaint.xls")); workbook.write(out); out.close(); System.out.println("Complaint written successfully.."); //</string></string,></string,> } catch (Exception e) { } }
From source file:ar.edu.unrc.gametictactoe.performanceandtraining.configurations.StatisticExperiment.java
License:Open Source License
/** * * @param filePath/* w w w.j av a 2s. c om*/ * @param backupFiles * @param resultsPerFile * @param resultsRandom * @param randomPerceptronFile <p> * @throws IOException * @throws InvalidFormatException */ public void exportToExcel(String filePath, List<File> backupFiles, Map<File, StatisticForCalc> resultsPerFile, Map<File, StatisticForCalc> resultsRandom, File randomPerceptronFile) throws IOException, InvalidFormatException { InputStream inputXLSX = this.getClass() .getResourceAsStream("/ar/edu/unrc/gametictactoe/resources/EstadisticasTicTacToe.xlsx"); Workbook wb = WorkbookFactory.create(inputXLSX); try (FileOutputStream outputXLSX = new FileOutputStream( filePath + "_" + dateFormater.format(dateForFileName) + "_STATISTICS" + ".xlsx")) { //============= imptimimos en la hoja de % Of Games Won =================== Sheet sheet = wb.getSheetAt(0); //Estilo par los titulos de las tablas int rowStartTitle = 0; int colStartTitle = 2; int rowStart = 1; int colStart = 3; Row rowPlayer1; Row rowPlayer2; Row rowDraw; // Luego creamos el objeto que se encargar de aplicar el estilo a la celda Font fontCellTitle = wb.createFont(); fontCellTitle.setFontHeightInPoints((short) 10); fontCellTitle.setFontName("Arial"); fontCellTitle.setBoldweight(Font.BOLDWEIGHT_BOLD); CellStyle CellStyleTitle = wb.createCellStyle(); CellStyleTitle.setWrapText(true); CellStyleTitle.setAlignment(CellStyle.ALIGN_CENTER); CellStyleTitle.setVerticalAlignment(CellStyle.VERTICAL_TOP); CellStyleTitle.setFont(fontCellTitle); // Establecemos el tipo de sombreado de nuestra celda CellStyleTitle.setFillBackgroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); CellStyleTitle.setFillPattern(CellStyle.SOLID_FOREGROUND); loadTitle(rowStartTitle, colStartTitle, sheet, backupFiles.size(), CellStyleTitle); //estilo titulo finalizado //Estilo de celdas con los valores de las estadisticas CellStyle cellStyle = wb.createCellStyle(); cellStyle.setWrapText(true); /* We are now ready to set borders for this style */ /* Draw a thin left border */ cellStyle.setBorderLeft(CellStyle.BORDER_THIN); /* Add medium right border */ cellStyle.setBorderRight(CellStyle.BORDER_THIN); /* Add dashed top border */ cellStyle.setBorderTop(CellStyle.BORDER_THIN); /* Add dotted bottom border */ cellStyle.setBorderBottom(CellStyle.BORDER_THIN); //estilo celdas finalizado //loadTitle(rowStartTitle, colStartTitle, sheet, backupFiles.size(), CellStyleTitle); rowPlayer1 = sheet.getRow(rowStart); rowPlayer2 = sheet.getRow(rowStart + 1); rowDraw = sheet.getRow(rowStart + 2); for (int file = 0; file < backupFiles.size(); file++) { Cell cellPlayer1 = rowPlayer1.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC); Cell cellPlayer2 = rowPlayer2.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC); Cell cellDraw = rowDraw.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC); cellPlayer1.setCellStyle(cellStyle); cellPlayer2.setCellStyle(cellStyle); cellDraw.setCellStyle(cellStyle); Double cellValuePlayer1 = resultsPerFile.get(backupFiles.get(file)).getWinRatePlayer1(); Double cellValuePlayer2 = resultsPerFile.get(backupFiles.get(file)).getWinRatePlayer2(); Double cellValueDraw = resultsPerFile.get(backupFiles.get(file)).getDrawRate(); assert cellValuePlayer1 <= 100 && cellValuePlayer1 >= 0; assert cellValuePlayer2 <= 100 && cellValuePlayer2 >= 0; assert cellValueDraw <= 100 && cellValueDraw >= 0; //assert cellValueDraw + cellValuePlayer1 + cellValuePlayer2 == 100; cellDraw.setCellValue(cellValueDraw); cellPlayer1.setCellValue(cellValuePlayer1); cellPlayer2.setCellValue(cellValuePlayer2); } if (!resultsRandom.isEmpty()) { int file = 0;//hay que ir a buscar el randomfile Cell cellDraw = rowDraw.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC); Cell cellPlayer1 = rowPlayer1.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC); Cell cellPlayer2 = rowPlayer2.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC); cellDraw.setCellStyle(cellStyle); cellPlayer1.setCellStyle(cellStyle); cellPlayer2.setCellStyle(cellStyle); // StatisticForCalc get = resultsRandom.get(randomPerceptronFile); // Double cellValuePlayer1 = get.getWinRatePlayer1(); Double cellValuePlayer1 = resultsRandom.get(randomPerceptronFile).getWinRatePlayer1(); Double cellValuePlayer2 = resultsRandom.get(randomPerceptronFile).getWinRatePlayer2(); Double cellValueDraw = resultsRandom.get(randomPerceptronFile).getDrawRate(); //assert cellValueDraw + cellValuePlayer1 + cellValuePlayer2 == 100; cellPlayer1.setCellValue(cellValuePlayer1); cellPlayer2.setCellValue(cellValuePlayer2); cellDraw.setCellValue(cellValueDraw); } wb.write(outputXLSX); } }
From source file:ar.edu.unrc.gametictactoe.performanceandtraining.configurations.StatisticExperiment.java
License:Open Source License
/** * * @param rowStartTitle/* w w w . j a va2 s .com*/ * @param colStartTitle * @param sheet * @param backupFilesSize * @param CellStyleTitle */ public void loadTitle(int rowStartTitle, int colStartTitle, Sheet sheet, int backupFilesSize, CellStyle CellStyleTitle) { int total_juegos = saveBackupEvery; Row row1 = sheet.getRow(rowStartTitle); for (int file = 1; file <= backupFilesSize; file++) { Cell cell = row1.createCell(file + colStartTitle, Cell.CELL_TYPE_NUMERIC); cell.setCellStyle(CellStyleTitle); Integer value = total_juegos * file; String valueStr = value.toString(); String cellV = valueStr; if (valueStr.length() > 3) { cellV = valueStr.substring(0, valueStr.length() - 3) + "K"; } cell.setCellValue(cellV); } }
From source file:archivocsv.models.Reporte.java
public static ArrayList<Reporte> generarReporteExcel(String anio, String mes) throws IOException { ArrayList<Reporte> archivoExcel = new ArrayList<>(); try {//from w w w .j a v a 2s . c o m FileChooser elegirArchivo = new FileChooser(); FileChooser.ExtensionFilter filtroExt = new FileChooser.ExtensionFilter("Archivos Excel (*.xls)", "*.xls"); elegirArchivo.getExtensionFilters().add(filtroExt); File archivo = elegirArchivo.showSaveDialog(archivoCsv.getVentanaPrincipal()); archivo.createNewFile(); Workbook libro = new HSSFWorkbook(); FileOutputStream enviar = new FileOutputStream(archivo); Sheet hoja = libro.createSheet("Reportes"); Sheet hoja2 = libro.createSheet("Entradas Tarde"); Row fila = hoja.createRow(0); Row fila2 = hoja2.createRow(0); for (int c = 0; c < 5; c++) { Cell celda = fila.createCell(c); if (c == 0) { celda.setCellValue("ID"); } if (c == 1) { celda.setCellValue("Nombre"); } if (c == 2) { celda.setCellValue("Entrada"); } if (c == 3) { celda.setCellValue("Salida"); } if (c == 4) { celda.setCellValue("Horas Trabajadas"); } } for (int c2 = 0; c2 < 3; c2++) { Cell celda2 = fila2.createCell(c2); if (c2 == 0) { celda2.setCellValue("ID"); } if (c2 == 1) { celda2.setCellValue("Nombre"); } if (c2 == 2) { celda2.setCellValue("Entrada"); } } Connection con = Helper.getConnection(); String entrada = "SELECT * FROM t_marcacion WHERE marcacion LIKE '%/" + mes + "/" + anio + "%'" + " AND marcacion LIKE '%a%'"; ResultSet rs = con.createStatement().executeQuery(entrada); ResultSet rs3 = con.createStatement().executeQuery(entrada); int contar = 0; int contar2 = 1; while (rs.next()) { contar += 1; Row filaDatos = hoja.createRow(contar); Cell celdaID = filaDatos.createCell(0); Cell celdaNombre = filaDatos.createCell(1); Cell celdaEntrada = filaDatos.createCell(2); Cell celdaSalida = filaDatos.createCell(3); Cell celdaHoras = filaDatos.createCell(4); Reporte reporte = new Reporte(); reporte.setEntrada(rs.getString("marcacion")); celdaEntrada.setCellValue(reporte.getEntrada()); reporte.setId(rs.getString("id")); celdaID.setCellValue(reporte.getId()); reporte.setNombre(rs.getString("nombre")); celdaNombre.setCellValue(reporte.getNombre()); //Query que verifica si existe el registro de salida String coincidir = "SELECT * FROM t_marcacion WHERE id=" + rs.getString("id") + " AND marcacion LIKE '%" + rs.getString("marcacion").substring(0, 10) + "%'" + " AND marcacion LIKE '%p%'"; ResultSet rs2 = con.createStatement().executeQuery(coincidir); if (rs2.next()) { reporte.setSalida(rs2.getString("marcacion")); celdaSalida.setCellValue(reporte.getSalida()); String horaInicial = rs.getString("marcacion").substring(11, 15) + " AM"; String horaFinal = rs2.getString("marcacion").substring(11, 15) + " PM"; if (horaFinal.substring(0, 2).equals("12")) { horaFinal = rs2.getString("marcacion").substring(11, 15) + " AM"; } DateFormat sdf = new SimpleDateFormat("KK:mm a"); Date date = sdf.parse(horaInicial); Date date2 = sdf.parse(horaFinal); double hrsInicialMs = date.getTime(); double hrsFinalMs = date2.getTime(); double diferencia = hrsFinalMs - hrsInicialMs; double resta = (diferencia / (1000 * 60 * 60)); int primerNumero = (int) resta; double segundoNumero = resta - primerNumero; int convertirNumero = (int) (segundoNumero * 60); int restarAlumerzo = primerNumero - 1; if (convertirNumero == 0) { reporte.setHorasTrabajadas(restarAlumerzo + ":00"); celdaHoras.setCellValue(reporte.getHorasTrabajadas()); } else { if (convertirNumero > 0 & convertirNumero < 10) { reporte.setHorasTrabajadas(restarAlumerzo + ":0" + convertirNumero); celdaHoras.setCellValue(reporte.getHorasTrabajadas()); } else { reporte.setHorasTrabajadas(restarAlumerzo + ":" + convertirNumero); celdaHoras.setCellValue(reporte.getHorasTrabajadas()); } } } else { reporte.setSalida("Sin registro"); celdaSalida.setCellValue(reporte.getSalida()); reporte.setHorasTrabajadas("Sin registro"); celdaHoras.setCellValue(reporte.getHorasTrabajadas()); } } while (rs3.next()) { Row filaDatos2 = hoja2.createRow(contar2); Cell celdaId = filaDatos2.createCell(0); Cell celdaNombre = filaDatos2.createCell(1); Cell celdaMarcacion = filaDatos2.createCell(2); Reporte reporte = new Reporte(); DateFormat sdf = new SimpleDateFormat("KK:mm a"); String horaInicio = "08:00 AM"; String horaFin = "12:00 PM"; String horaEntrada = rs3.getString("marcacion"); if (horaEntrada.substring(11, 12).equals("0")) { horaEntrada = rs3.getString("marcacion").substring(11, 16) + " AM"; } else { if (horaEntrada.substring(11, 13).equals("10") || horaEntrada.substring(11, 13).equals("11")) { horaEntrada = rs3.getString("marcacion").substring(11, 16) + " AM"; } else { horaEntrada = rs3.getString("marcacion").substring(11, 15) + " AM"; } } Date hrInicio = sdf.parse(horaInicio); Date hrFin = sdf.parse(horaFin); Date hrEntrada = sdf.parse(horaEntrada); Calendar calInicio = new GregorianCalendar(); Calendar calFin = new GregorianCalendar(); Calendar calEntrada = new GregorianCalendar(); calInicio.setTime(hrInicio); calFin.setTime(hrFin); calEntrada.setTime(hrEntrada); if (calEntrada.after(calInicio) & calEntrada.before(calFin)) { contar2 += 1; reporte.setId(rs3.getString("id")); celdaId.setCellValue(reporte.getId()); reporte.setNombre(rs3.getString("nombre")); celdaNombre.setCellValue(reporte.getNombre()); reporte.setEntrada(rs3.getString("marcacion")); celdaMarcacion.setCellValue(reporte.getEntrada()); archivoExcel.add(reporte); } } hoja.setColumnWidth(0, 850); hoja.setColumnWidth(1, 3000); hoja.setColumnWidth(2, 6000); hoja.setColumnWidth(3, 6000); hoja.setColumnWidth(4, 4000); hoja2.setColumnWidth(0, 850); hoja2.setColumnWidth(1, 3000); hoja2.setColumnWidth(2, 6000); libro.write(enviar); enviar.close(); Desktop.getDesktop().open(archivo); } catch (Exception e) { } return archivoExcel; }
From source file:at.fh.swenga.firefighters.report.ExcelFireEngineReportView.java
@Override protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { List<FireEngineModel> fireEngines = (List<FireEngineModel>) model.get("fireEngines"); // create a worksheet Sheet sheet = workbook.createSheet("FireEngine Report"); // create style for header cells CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setFontName("Arial"); style.setFillForegroundColor(HSSFColor.BLUE.index); style.setFillPattern(CellStyle.SOLID_FOREGROUND); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); font.setColor(HSSFColor.WHITE.index); style.setFont(font);//from w w w .j a v a 2 s . c om // create a new row in the worksheet Row headerRow = sheet.createRow(0); // create a new cell in the row Cell cell0 = headerRow.createCell(0); cell0.setCellValue("ID"); cell0.setCellStyle(style); // create a new cell in the row Cell cell1 = headerRow.createCell(1); cell1.setCellValue("Modell"); cell1.setCellStyle(style); // create a new cell in the row Cell cell2 = headerRow.createCell(2); cell2.setCellValue("Kennzeichen"); cell2.setCellStyle(style); // create a new cell in the row Cell cell3 = headerRow.createCell(3); cell3.setCellValue("Leistung"); cell3.setCellStyle(style); // create a new cell in the row Cell cell4 = headerRow.createCell(4); cell4.setCellValue("Baujahr"); cell4.setCellStyle(style); // create a new cell in the row Cell cell5 = headerRow.createCell(5); cell5.setCellValue("Aktiv"); cell5.setCellStyle(style); // create a new cell in the row Cell cell6 = headerRow.createCell(6); cell6.setCellValue("Funktion"); cell6.setCellStyle(style); // create a new cell in the row Cell cell7 = headerRow.createCell(7); cell7.setCellValue("Feuerwehr"); cell7.setCellStyle(style); // create multiple rows with fireEngines data int rowNum = 1; for (FireEngineModel fireEngine : fireEngines) { // create the row data Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(fireEngine.getId()); row.createCell(1).setCellValue(fireEngine.getModel()); row.createCell(2).setCellValue(fireEngine.getLicensePlate()); row.createCell(3).setCellValue(fireEngine.getPerformance()); row.createCell(4).setCellValue(fireEngine.getBuildYear()); row.createCell(5).setCellValue(fireEngine.getActive()); row.createCell(6).setCellValue(fireEngine.getAbbreviation().getAbbreviation()); row.createCell(7).setCellValue(fireEngine.getFireBrigade().getName()); } // adjust column width to fit the content sheet.autoSizeColumn((short) 0); sheet.autoSizeColumn((short) 1); sheet.autoSizeColumn((short) 2); sheet.autoSizeColumn((short) 3); sheet.autoSizeColumn((short) 4); sheet.autoSizeColumn((short) 5); sheet.autoSizeColumn((short) 6); sheet.autoSizeColumn((short) 7); }
From source file:at.mukprojects.exclycore.model.ExclyDate.java
License:Open Source License
@Override public void setCell(Cell cell, CellStyle cellStyle) { cell.setCellValue(data); cell.setCellStyle(cellStyle); }
From source file:at.mukprojects.exclycore.model.ExclyDateError.java
License:Open Source License
@Override public void setCell(Cell cell, CellStyle cellStyle) { cell.setCellValue(ERRORCODE); CellStyle cellStyleError = cell.getSheet().getWorkbook().createCellStyle(); cellStyleError.cloneStyleFrom(cellStyle); cellStyleError.setFillForegroundColor(IndexedColors.RED.getIndex()); cellStyleError.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); cell.setCellStyle(cellStyleError);/* ww w . java 2 s. c o m*/ }
From source file:au.gov.ansto.bragg.quokka.experiment.util.ExperimentModelUtils.java
License:Open Source License
public static void saveExperimentToExcel(Experiment experiment, String filename) throws IOException { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("Quokka Multi-Sample Scan"); int rowCounter = 0; if (experiment.isControlledEnvironment()) { for (ControlledAcquisition acquisition : experiment.getAcquisitionGroups()) { for (SampleEnvironment sampleEnvironment : experiment.getSampleEnvironments()) { Row row = sheet.createRow(rowCounter++); Cell cell = row.createCell(0); cell.setCellValue(sampleEnvironment.getControllerId()); cell = row.createCell(1); cell.setCellValue(acquisition.getEnvSettings().get(sampleEnvironment).getPreset()); }/* ww w .j a va2 s . co m*/ rowCounter = saveAcquisitionToExcel(acquisition, sheet, rowCounter); } } else { rowCounter = saveAcquisitionToExcel(experiment.getNormalAcquisition(), sheet, rowCounter); } FileOutputStream fileOut = new FileOutputStream(filename); workbook.write(fileOut); fileOut.close(); }