List of usage examples for org.apache.poi.ss.usermodel Workbook getFontAt
Font getFontAt(int idx);
From source file:CellStyleDetails.java
License:Apache License
public static void main(String[] args) throws Exception { if (args.length == 0) { throw new IllegalArgumentException("Filename must be given"); }/*from w ww.ja v a 2s .co m*/ Workbook wb = WorkbookFactory.create(new File(args[0])); DataFormatter formatter = new DataFormatter(); for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) { Sheet sheet = wb.getSheetAt(sn); System.out.println("Sheet #" + sn + " : " + sheet.getSheetName()); for (Row row : sheet) { System.out.println(" Row " + row.getRowNum()); for (Cell cell : row) { CellReference ref = new CellReference(cell); System.out.print(" " + ref.formatAsString()); System.out.print(" (" + cell.getColumnIndex() + ") "); CellStyle style = cell.getCellStyle(); System.out.print("Format=" + style.getDataFormatString() + " "); System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " "); System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " "); Font font = wb.getFontAt(style.getFontIndex()); System.out.print("Font=" + font.getFontName() + " "); System.out.print("FontColor="); if (font instanceof HSSFFont) { System.out.print(renderColor(((HSSFFont) font).getHSSFColor((HSSFWorkbook) wb))); } if (font instanceof XSSFFont) { System.out.print(renderColor(((XSSFFont) font).getXSSFColor())); } System.out.println(); System.out.println(" " + formatter.formatCellValue(cell)); } } System.out.println(); } }
From source file:bad.robot.excel.style.ReplaceExistingStyle.java
License:Apache License
private void applyFontTo(CellStyle style, Workbook workbook) { if (fontSize != null) { Font font = workbook.createFont(); font.setFontHeightInPoints(fontSize.value()); font.setColor(fontColour.value().getPoiStyle()); style.setFont(font);// w w w. j a v a2 s . c o m } else { // doesn't work Font existing = workbook.getFontAt(style.getFontIndex()); existing.setColor(fontColour.value().getPoiStyle()); style.setFont(existing); } }
From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java
License:Open Source License
private static Chunk getChunk(Workbook wb, Cell cell) { Chunk phrase = null;/*from w w w . ja va 2 s.c om*/ switch (cell.getCellType() == Cell.CELL_TYPE_FORMULA ? cell.getCachedFormulaResultType() : cell.getCellType()) { case Cell.CELL_TYPE_STRING: phrase = new Chunk("" + cell.getStringCellValue()); break; case Cell.CELL_TYPE_NUMERIC: String format = cell.getCellStyle().getDataFormatString(); if (cell.getCellStyle().getDataFormat() > 0) { try { if (format.contains("0")) { //Decimal DecimalFormat df = new DecimalFormat(format); phrase = new Chunk(df.format(cell.getNumericCellValue())); } else if (format.contains("h:")) { phrase = new Chunk(FormatterUtils.formatDateTimeShort(cell.getDateCellValue())); } else if (format.contains("yy")) { phrase = new Chunk(FormatterUtils.formatDate(cell.getDateCellValue())); } } catch (Exception e) { System.err.println(e); } } if (phrase == null) { phrase = new Chunk("" + (int) cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BLANK: phrase = new Chunk(""); break; default: phrase = new Chunk("" + cell.getCellType()); } Font font = wb.getFontAt(cell.getCellStyle().getFontIndex()); short[] rgb = HSSFColor.getIndexHash().get((int) font.getColor()).getTriplet(); phrase.setFont(new com.lowagie.text.Font(phrase.getFont().getBaseFont(), font.getFontHeightInPoints() - 3, (font.getBold() ? com.lowagie.text.Font.BOLD : com.lowagie.text.Font.NORMAL), new Color(rgb[0], rgb[1], rgb[2]))); return phrase; }
From source file:com.b2international.snowowl.datastore.server.importer.ExcelUtilities.java
License:Apache License
/** * Returns true if the cell (NOT the text inside) is set to bold. * @param cell/*from ww w .j av a2s . c o m*/ * @return */ public static boolean isBold(Cell cell) { CellStyle style = cell.getCellStyle(); Workbook workBook = cell.getSheet().getWorkbook(); Font font = workBook.getFontAt(style.getFontIndex()); XSSFFont xssfFont = (XSSFFont) font; return xssfFont.getBold(); }
From source file:com.helger.poi.excel.style.ExcelStyle.java
License:Apache License
public void fillCellStyle(@Nonnull final Workbook aWB, @Nonnull final CellStyle aCS, @Nonnull final CreationHelper aCreationHelper) { if (m_eAlign != null) aCS.setAlignment(m_eAlign.getValue()); if (m_eVAlign != null) aCS.setVerticalAlignment(m_eVAlign.getValue()); aCS.setWrapText(m_bWrapText);//from w ww . j a va2 s . co m if (m_sDataFormat != null) aCS.setDataFormat(aCreationHelper.createDataFormat().getFormat(m_sDataFormat)); if (m_eFillBackgroundColor != null) aCS.setFillBackgroundColor(m_eFillBackgroundColor.getIndex()); if (m_eFillForegroundColor != null) aCS.setFillForegroundColor(m_eFillForegroundColor.getIndex()); if (m_eFillPattern != null) aCS.setFillPattern(m_eFillPattern.getValue()); if (m_eBorderTop != null) aCS.setBorderTop(m_eBorderTop.getValue()); if (m_eBorderRight != null) aCS.setBorderRight(m_eBorderRight.getValue()); if (m_eBorderBottom != null) aCS.setBorderBottom(m_eBorderBottom.getValue()); if (m_eBorderLeft != null) aCS.setBorderLeft(m_eBorderLeft.getValue()); if (m_nFontIndex >= 0) aCS.setFont(aWB.getFontAt(m_nFontIndex)); }
From source file:com.ocs.dynamo.ui.composite.table.export.TableExportActionHandlerTest.java
License:Apache License
@Test public void testExportWithCustomCellStyle() throws IOException { List<EntityModel<?>> models = new ArrayList<>(); models.add(entityModelFactory.getModel(Person.class)); handler = new TableExportActionHandler(ui, entityModelFactory, models, messageService, REPORT_TITLE, columnIds, true, new CustomCellStyleGenerator() { private CellStyle cellStyle; private CellStyle bdStyle; @Override// w ww. ja v a2 s . c o m public CellStyle getCustomCellStyle(Workbook workbook, Object propId, Object value, AttributeModel attributeModel) { if (cellStyle == null) { cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_RIGHT); cellStyle.setBorderBottom(CellStyle.BORDER_THIN); cellStyle.setBorderTop(CellStyle.BORDER_THIN); cellStyle.setBorderLeft(CellStyle.BORDER_THIN); cellStyle.setBorderRight(CellStyle.BORDER_THIN); Font font = workbook.createFont(); font.setColor(IndexedColors.BLUE.getIndex()); cellStyle.setFont(font); } if (bdStyle == null) { DataFormat format = workbook.createDataFormat(); bdStyle = workbook.createCellStyle(); bdStyle.setAlignment(CellStyle.ALIGN_RIGHT); bdStyle.setBorderBottom(CellStyle.BORDER_THIN); bdStyle.setBorderTop(CellStyle.BORDER_THIN); bdStyle.setBorderLeft(CellStyle.BORDER_THIN); bdStyle.setBorderRight(CellStyle.BORDER_THIN); bdStyle.setDataFormat(format.getFormat("#,##0.00")); Font font = workbook.createFont(); font.setColor(IndexedColors.BLUE.getIndex()); bdStyle.setFont(font); } if ("name".equals(propId)) { return cellStyle; } else if ("percentage".equals(propId)) { return bdStyle; } return null; } }); handler.handleAction(handler.getActions(null, null)[0], getTable(), null); byte[] bytes = captureSave(); Workbook wb = importer.createWorkbook(bytes); Assert.assertEquals("Bas, Bob", wb.getSheetAt(0).getRow(2).getCell(0).getStringCellValue()); Font font = wb.getFontAt(wb.getSheetAt(0).getRow(2).getCell(0).getCellStyle().getFontIndex()); Assert.assertEquals(IndexedColors.BLUE.getIndex(), font.getColor()); Assert.assertEquals("Patrick", wb.getSheetAt(0).getRow(3).getCell(0).getStringCellValue()); Assert.assertEquals(35, wb.getSheetAt(0).getRow(2).getCell(1).getNumericCellValue(), 0.001); Assert.assertEquals(44, wb.getSheetAt(0).getRow(3).getCell(1).getNumericCellValue(), 0.001); // totals must be summed up Assert.assertEquals(79, wb.getSheetAt(0).getRow(4).getCell(1).getNumericCellValue(), 0.001); // percentage Assert.assertEquals(0.12, wb.getSheetAt(0).getRow(2).getCell(3).getNumericCellValue(), 0.001); Assert.assertEquals(0.15, wb.getSheetAt(0).getRow(3).getCell(3).getNumericCellValue(), 0.001); }
From source file:de.thb.ue.backend.util.EvaluationExcelFileGenerator.java
License:Apache License
public void generateExcelFile() { Row row;/* ww w . j ava 2 s.co m*/ Cell cell; int yOffset = 1; File workingDirectory = new File( (workingDirectoryPath.isEmpty() ? "" : (workingDirectoryPath + File.separatorChar)) + evaluationUID); if (!workingDirectory.exists()) { workingDirectory.mkdir(); } File file = new File(workingDirectory, "auswertung.xls"); try { FileOutputStream out = new FileOutputStream(file); Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("Evaluation"); // configure cell styles configureCellStyles(wb); /* * ********************************** * begin formatting document * ********************************** * */ //construct first row of infopanel yOffset = constructInfoPanelRow("Lehrveranstaltung", subject, numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.topLeftCorner, InfoPanelBorderStyles.top, InfoPanelBorderStyles.topRightCorner); //construct second row of infopanel yOffset = constructInfoPanelRow("Semester", semesterType == SemesterType.WINTER ? "Winter" : "Sommer", numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.left, InfoPanelBorderStyles.none, InfoPanelBorderStyles.right); //construct third row of infopanel StringBuilder tutors = new StringBuilder(); for (int i = 0; i < this.tutors.size(); i++) { if (i + 1 < this.tutors.size()) { tutors.append(this.tutors.get(i)).append(", "); } else { tutors.append(this.tutors.get(i)); } } yOffset = constructInfoPanelRow("Lehrende(r)", tutors.toString(), numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.left, InfoPanelBorderStyles.none, InfoPanelBorderStyles.right); //construct fourth row of infopanel yOffset = constructInfoPanelRow("Datum der Befragung", dateOfEvaluation.toString("dd.MM.yy HH:mm"), numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.left, InfoPanelBorderStyles.none, InfoPanelBorderStyles.right); //construct fifth row of infopanel yOffset = constructInfoPanelRow("Anzahl der Teilnehmer", Integer.toString(numberStudentsAll), numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.left, InfoPanelBorderStyles.none, InfoPanelBorderStyles.right); //construct sixth row of infopanel () last yOffset = constructInfoPanelRow("Anzahl der ausgefllten Fragebgen", Integer.toString(numberStudentsVoted), numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.bottomLeftCorner, InfoPanelBorderStyles.bottom, InfoPanelBorderStyles.bottomRightCorner); //begin construction of evaluationPanel yOffset++; row = sheet.createRow(yOffset); cell = row.createCell(1, Cell.CELL_TYPE_STRING); cell.setCellValue("Frage"); cell.setCellStyle(headerStyle); cell = row.createCell(2, Cell.CELL_TYPE_STRING); cell.setCellValue("MW"); cell.setCellStyle(headerStyle); cell = row.createCell(3, Cell.CELL_TYPE_STRING); cell.setCellValue("Ifd NR."); cell.setCellStyle(headerStyle); cell = row.createCell(4); cell.setCellStyle(commonStyle); // add count of valid evaluations (how many students voted) (horizontal) for (int i = 0; i < numberStudentsVoted; i++) { cell = row.createCell(i + 5); cell.setCellValue(i + 1); sheet.setColumnWidth(cell.getColumnIndex(), 4 * 256); cell.setCellStyle(headerStyle); } // get letter of last student column CellReference cellReference = new CellReference(cell.getRowIndex(), cell.getColumnIndex()); String endCellName = cellReference.getCellRefParts()[2]; Row headRow = row; for (int i = 1; i < mcQuestionTexts.size() + 1; i++) { //add number of questions row = sheet.createRow(i + yOffset); cell = row.createCell(1, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(i); cell.setCellStyle(commonStyle); //add average formula cell = row.createCell(2, Cell.CELL_TYPE_FORMULA); //formlua works with blanks, empty strings and negative values String formula = "SUMPRODUCT(ABS(N(+F" + (i + yOffset + 1) + ":" + endCellName + (i + yOffset + 1) + ")))/COUNT(F" + (i + yOffset + 1) + ":" + endCellName + (i + yOffset + 1) + ")"; //String averageFormula = "AVERAGE(IF(F" + (i + yOffset + 1) + ":" + endCellName + (i + yOffset + 1) + "<>\"\", ABS(F" + (i + yOffset + 1) + ":" + endCellName + (i + yOffset + 1) + ")))"; cell.setCellFormula(formula); cell.setCellStyle(commonStyle); //fill blank cells cell = row.createCell(3); cell.setCellStyle(commonStyle); //add question texts sheet.setColumnWidth(4, findLongestString(mcQuestionTexts) * 256 * (wb.getFontAt(questionStyle.getFontIndex()).getFontHeightInPoints()) / 10); cell = row.createCell(4, Cell.CELL_TYPE_STRING); cell.setCellValue(mcQuestionTexts.get(i - 1)); cell.setCellStyle(questionStyle); } //add student votes for (int i = 0; i < studentVotes.size(); i++) { Vote vote = studentVotes.get(i); for (int k = 0; k < mcQuestionTexts.size(); k++) { row = sheet.getRow(headRow.getRowNum() + 1 + k); cell = row.createCell(5 + i); for (MCAnswer answer : vote.getMcAnswers()) { //if question of inner loop equals question of outer loop we found // the correct question for this cell if (answer.getQuestion().getText().equals(mcQuestionTexts.get(k))) { Choice choice = answer.getChoice(); if (choice != null && choice.getGrade() != 0) { cell = colorizeCell(cell, wb, choice.getGrade()); cell.setCellValue(answer.getChoice().getGrade()); } else { cell = colorizeCell(cell, wb, -1); cell.setCellValue(""); } } } } } // include textual answers createTextualAnswers(studentVotes, textualQuestionTexts, sheet, wb); wb.write(out); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:de.thb.ue.backend.util.EvaluationExcelFileGenerator.java
License:Apache License
private void createTextualAnswers(@NonNull List<Vote> answers, @NonNull List<String> questionTexts, Sheet sheet, Workbook wb) { Row row;/*from w ww .j av a2s .c o m*/ Cell cell; row = sheet.createRow(sheet.getLastRowNum() + 2); cell = row.createCell(1); CellStyle helpStyle = wb.createCellStyle(); helpStyle.cloneStyleFrom(headerStyle); helpStyle.setBorderBottom(CellStyle.BORDER_NONE); helpStyle.setBorderTop(CellStyle.BORDER_NONE); helpStyle.setBorderLeft(CellStyle.BORDER_NONE); helpStyle.setBorderRight(CellStyle.BORDER_NONE); cell.setCellValue("Kommentare"); cell.setCellStyle(helpStyle); //TODO used to determine style for current line -> its stupid. Think of something better int styleCounter = 0; for (String textualQuestion : questionTexts) { row = sheet.createRow(sheet.getLastRowNum() + 3); cell = row.createCell(1); cell.setCellValue(textualQuestion); setTextQuestionStyle(cell, styleCounter, true); //colorize horizontal neighbour cells of headline for (int i = 2; i < 5; i++) { cell = row.createCell(i); setTextQuestionStyle(cell, styleCounter, false); } int rowNum = sheet.getLastRowNum(); int counter = 1; for (String comment : aggregateTextAnswers(answers, textualQuestion)) { row = sheet.createRow(rowNum + 1); cell = row.createCell(1, Cell.CELL_TYPE_STRING); // introduces line breaks in long comments ArrayList<String> commentChunks = splitComment(comment); StringBuilder formattedComment = new StringBuilder(); formattedComment.append(Integer.toString(counter)); formattedComment.append(": "); int chunkCounter = 0; for (String chunk : commentChunks) { formattedComment.append(chunk); if ((chunkCounter + 1) < commentChunks.size()) { formattedComment.append(System.lineSeparator()); } chunkCounter++; } cell.setCellValue(formattedComment.toString()); CellStyle style = setTextQuestionStyle(cell, styleCounter, false); // increase height of row based on font size, number of lines and line spacing // the origin of 140 % -> http://superuser.com/questions/337181/how-many-pts-is-1-5-line-spacing-in-microsoft-word-2007 float pointsPerLine = (wb.getFontAt(style.getFontIndex()).getFontHeightInPoints() * 140) / 100; row.setHeightInPoints(pointsPerLine * commentChunks.size()); //colorize horizontal neighbour cells of comment for (int i = 2; i < 17; i++) { cell = row.createCell(i); setTextQuestionStyle(cell, styleCounter, false); } sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), 1, 17)); rowNum++; counter++; } styleCounter++; } }
From source file:guru.qas.martini.report.DefaultState.java
License:Apache License
public void updateLongestExecutions() { if (!longestExecutionCells.isEmpty()) { for (Cell cell : longestExecutionCells) { CellStyle original = cell.getCellStyle(); Sheet sheet = cell.getSheet(); Workbook workbook = sheet.getWorkbook(); CellStyle newStyle = workbook.createCellStyle(); newStyle.cloneStyleFrom(original); int originalFontIndex = original.getFontIndexAsInt(); Font originalFont = workbook.getFontAt(originalFontIndex); Font font = workbook.createFont(); font.setBold(true);/* w ww. ja v a 2 s.c o m*/ font.setColor(IndexedColors.DARK_RED.getIndex()); font.setFontHeight((short) Math.round(originalFont.getFontHeight() * 1.5)); newStyle.setFont(font); cell.setCellStyle(newStyle); Row row = cell.getRow(); short firstCellNum = row.getFirstCellNum(); short lastCellNum = row.getLastCellNum(); for (int i = firstCellNum; i < lastCellNum; i++) { Cell rowCell = row.getCell(i); original = rowCell.getCellStyle(); CellStyle borderStyle = workbook.createCellStyle(); borderStyle.cloneStyleFrom(original); borderStyle.setBorderTop(BorderStyle.MEDIUM); borderStyle.setBorderBottom(BorderStyle.MEDIUM); if (i == cell.getColumnIndex()) { borderStyle.setBorderLeft(BorderStyle.MEDIUM); borderStyle.setBorderRight(BorderStyle.MEDIUM); } else if (i == firstCellNum) { borderStyle.setBorderLeft(BorderStyle.MEDIUM); } else if (i == lastCellNum - 1) { borderStyle.setBorderRight(BorderStyle.MEDIUM); } rowCell.setCellStyle(borderStyle); } } } }
From source file:guru.qas.martini.report.DefaultState.java
License:Apache License
protected void colorCompromisedThemes() { Collection<Cell> failed = statii.get("FAILED"); if (!failed.isEmpty()) { List<Row> rows = Lists.newArrayListWithExpectedSize(failed.size()); for (Cell cell : failed) { Row row = cell.getRow();/*from ww w . ja va2 s. c om*/ rows.add(row); } Set<Cell> compromisedThemeCells = Sets.newHashSet(); Map<String, Collection<Cell>> themeMap = themes.asMap(); for (Map.Entry<String, Collection<Cell>> mapEntry : themeMap.entrySet()) { Collection<Cell> themeCells = mapEntry.getValue(); boolean compromised = false; for (Iterator<Cell> iterator = themeCells.iterator(); !compromised && iterator.hasNext();) { Cell themeCell = iterator.next(); Row row = themeCell.getRow(); compromised = rows.contains(row); } if (compromised) { compromisedThemeCells.addAll(themeCells); } } Set<String> compromisedThemes = Sets.newHashSet(); for (Cell themeCell : compromisedThemeCells) { String contents = themeCell.getStringCellValue(); if (null != contents) { Iterable<String> themes = Splitter.onPattern("\\s+").omitEmptyStrings().split(contents); Iterables.addAll(compromisedThemes, themes); } } for (String theme : compromisedThemes) { Collection<Cell> cells = themes.get(theme); for (Cell cell : cells) { CellStyle cellStyle = cell.getCellStyle(); Sheet sheet = cell.getSheet(); Workbook workbook = sheet.getWorkbook(); int originalFontIndex = cellStyle.getFontIndexAsInt(); Font originalFont = workbook.getFontAt(originalFontIndex); CellStyle clone = workbook.createCellStyle(); clone.cloneStyleFrom(cellStyle); Font font = workbook.findFont(true, IndexedColors.DARK_RED.getIndex(), originalFont.getFontHeight(), originalFont.getFontName(), originalFont.getItalic(), originalFont.getStrikeout(), originalFont.getTypeOffset(), originalFont.getUnderline()); if (null == font) { font = workbook.createFont(); font.setBold(true); font.setColor(IndexedColors.DARK_RED.getIndex()); font.setFontHeight(originalFont.getFontHeight()); font.setFontName(originalFont.getFontName()); font.setItalic(originalFont.getItalic()); font.setStrikeout(originalFont.getStrikeout()); font.setTypeOffset(originalFont.getTypeOffset()); font.setUnderline(originalFont.getUnderline()); } clone.setFont(font); cell.setCellStyle(clone); } } } }