List of usage examples for org.apache.poi.ss.usermodel Font setBold
public void setBold(boolean bold);
From source file:org.primefaces.extensions.showcase.util.ExcelCustomExporter.java
License:Apache License
@Override public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle, boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor, MethodExpression postProcessor, boolean subTable) throws IOException { wb = new XSSFWorkbook(); String safeName = WorkbookUtil.createSafeSheetName(filename); Sheet sheet = wb.createSheet(safeName); cellStyle = wb.createCellStyle();/*from w w w .ja v a2 s . c o m*/ facetStyle = wb.createCellStyle(); titleStyle = wb.createCellStyle(); createCustomFonts(); int maxColumns = 0; StringTokenizer st = new StringTokenizer(tableId, ","); while (st.hasMoreElements()) { String tableName = (String) st.nextElement(); UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(), tableName); if (component == null) { throw new FacesException("Cannot find component \"" + tableName + "\" in view."); } if (!(component instanceof DataTable || component instanceof DataList)) { throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName() + "\", exporter must target a PrimeFaces DataTable/DataList."); } DataList list = null; DataTable table = null; int cols = 0; if (preProcessor != null) { preProcessor.invoke(context.getELContext(), new Object[] { wb }); } if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) { Row titleRow = sheet.createRow(sheet.getLastRowNum()); int cellIndex = titleRow.getLastCellNum() == -1 ? 0 : titleRow.getLastCellNum(); Cell cell = titleRow.createCell(cellIndex); cell.setCellValue(new XSSFRichTextString(tableTitle)); Font titleFont = wb.createFont(); titleFont.setBold(true); titleStyle.setFont(titleFont); cell.setCellStyle(titleStyle); sheet.createRow(sheet.getLastRowNum() + 3); } if (component instanceof DataList) { list = (DataList) component; if (list.getHeader() != null) { tableFacet(context, sheet, list, "header"); } if (pageOnly) { exportPageOnly(context, list, sheet); } else { exportAll(context, list, sheet); } cols = list.getRowCount(); } else { table = (DataTable) component; int columnsCount = getColumnsCount(table); if (table.getHeader() != null && !subTable) { tableFacet(context, sheet, table, columnsCount, "header"); } if (!subTable) { tableColumnGroup(sheet, table, "header"); } addColumnFacets(table, sheet, ColumnType.HEADER); if (pageOnly) { exportPageOnly(context, table, sheet); } else if (selectionOnly) { exportSelectionOnly(context, table, sheet); } else { exportAll(context, table, sheet, subTable); } if (table.hasFooterColumn() && !subTable) { addColumnFacets(table, sheet, ColumnType.FOOTER); } if (!subTable) { tableColumnGroup(sheet, table, "footer"); } table.setRowIndex(-1); if (postProcessor != null) { postProcessor.invoke(context.getELContext(), new Object[] { wb }); } cols = table.getColumnsCount(); if (maxColumns < cols) { maxColumns = cols; } } sheet.createRow(sheet.getLastRowNum() + Integer.parseInt(datasetPadding)); } if (!subTable) { for (int i = 0; i < maxColumns; i++) { sheet.autoSizeColumn((short) i); } } PrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(true); printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE); sheet.setPrintGridlines(true); writeExcelToResponse(context.getExternalContext(), wb, filename); }
From source file:org.primefaces.extensions.showcase.util.ExcelCustomExporter.java
License:Apache License
protected void createCustomFonts() { Font facetFont = wb.createFont(); Font cellFont = wb.createFont(); if (cellFontColor != null) { XSSFColor cellColor = new XSSFColor(cellFontColor); ((XSSFFont) cellFont).setColor(cellColor); }/*from ww w . jav a 2 s.com*/ if (cellFontSize != null) { cellFont.setFontHeightInPoints(cellFontSize); } if (cellFontStyle.equalsIgnoreCase("BOLD")) { cellFont.setBold(true); } if (cellFontStyle.equalsIgnoreCase("ITALIC")) { cellFont.setItalic(true); } if (facetFontStyle.equalsIgnoreCase("BOLD")) { facetFont.setBold(true); } if (facetFontStyle.equalsIgnoreCase("ITALIC")) { facetFont.setItalic(true); } if (fontName != null) { cellFont.setFontName(fontName); facetFont.setFontName(fontName); } cellStyle.setFont(cellFont); if (facetBackground != null) { XSSFColor backgroundColor = new XSSFColor(facetBackground); ((XSSFCellStyle) facetStyle).setFillForegroundColor(backgroundColor); facetStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); } if (facetFontColor != null) { XSSFColor facetColor = new XSSFColor(facetFontColor); ((XSSFFont) facetFont).setColor(facetColor); } if (facetFontSize != null) { facetFont.setFontHeightInPoints(facetFontSize); } facetStyle.setFont(facetFont); facetStyle.setAlignment(HorizontalAlignment.CENTER); }
From source file:org.sakaiproject.evaluation.tool.reporting.XLSReportExporter.java
License:Educational Community License
/** * Build the .xls report in the new (section based) format. * /*www. j a v a2s. c om*/ * @param evaluation * @param groupIDs * @param outputStream */ private void buildReportSectionAware(EvalEvaluation evaluation, String[] groupIDs, OutputStream outputStream) { // Get permission to view, current user and eval owner Boolean instructorViewAllResults = evaluation.getInstructorViewAllResults(); String currentUserId = commonLogic.getCurrentUserId(); String evalOwner = evaluation.getOwner(); TemplateItemDataList tidl = getEvalTIDL(evaluation, groupIDs); List<DataTemplateItem> dtiList = tidl.getFlatListOfDataTemplateItems(true); Workbook wb = new XSSFWorkbook(); creationHelper = wb.getCreationHelper(); // Title style Sheet courseSheet = wb.createSheet(messageLocator.getMessage("viewreport.xls.courseSheet.name")); Sheet instructorSheet = wb.createSheet(messageLocator.getMessage("viewreport.xls.instructorSheet.name")); Font font = wb.createFont(); font.setFontHeightInPoints((short) 12); font.setBold(true); CellStyle mainTitleStyle = wb.createCellStyle(); mainTitleStyle.setFont(font); // Bold header style font = wb.createFont(); font.setFontHeightInPoints((short) 10); font.setBold(true); CellStyle boldHeaderStyle = wb.createCellStyle(); boldHeaderStyle.setFont(font); // Italic meta header style font = wb.createFont(); font.setFontHeightInPoints((short) 10); font.setItalic(true); CellStyle italicMiniHeaderStyle = wb.createCellStyle(); italicMiniHeaderStyle.setFont(font); // Date meta Style dateCellStyle = wb.createCellStyle(); dateCellStyle.setDataFormat((short) 0x16); // Evaluation Title int rowCounter = 0; Row courseSheetRow1 = courseSheet.createRow(rowCounter); Row instructorSheetRow1 = instructorSheet.createRow(rowCounter); Cell courseSheetCellA1 = courseSheetRow1.createCell((short) 0); Cell instructorSheetCellA1 = instructorSheetRow1.createCell((short) 0); setPlainStringCell(courseSheetCellA1, evaluation.getTitle() + " - " + messageLocator.getMessage("viewreport.xls.courseSheet.name")); setPlainStringCell(instructorSheetCellA1, evaluation.getTitle() + " - " + messageLocator.getMessage("viewreport.xls.instructorSheet.name")); courseSheetCellA1.setCellStyle(mainTitleStyle); instructorSheetCellA1.setCellStyle(mainTitleStyle); // Calculate the response rate rowCounter++; int responsesCount = evaluationService.countResponses(null, new Long[] { evaluation.getId() }, groupIDs, null); int enrollmentsCount = evaluationService.countParticipantsForEval(evaluation.getId(), groupIDs); Row courseSheetRow2 = courseSheet.createRow(rowCounter); Row instructorSheetRow2 = instructorSheet.createRow(rowCounter); Cell courseSheetCellA2 = courseSheetRow2.createCell((short) 0); Cell instructorSheetCellA2 = instructorSheetRow2.createCell((short) 0); courseSheetCellA2.setCellStyle(boldHeaderStyle); instructorSheetCellA2.setCellStyle(boldHeaderStyle); setPlainStringCell(courseSheetCellA2, EvalUtils.makeResponseRateStringFromCounts(responsesCount, enrollmentsCount)); setPlainStringCell(instructorSheetCellA2, EvalUtils.makeResponseRateStringFromCounts(responsesCount, enrollmentsCount)); // Dates setPlainStringCell(courseSheetRow1.createCell((short) 2), messageLocator.getMessage("evalsettings.start.date.header")); setPlainStringCell(instructorSheetRow1.createCell((short) 2), messageLocator.getMessage("evalsettings.start.date.header")); setDateCell(courseSheetRow2.createCell((short) 2), evaluation.getStartDate()); setDateCell(instructorSheetRow2.createCell((short) 2), evaluation.getStartDate()); if (evaluation.getDueDate() != null) { setPlainStringCell(courseSheetRow1.createCell((short) 3), messageLocator.getMessage("evalsettings.due.date.header")); setPlainStringCell(instructorSheetRow1.createCell((short) 3), messageLocator.getMessage("evalsettings.due.date.header")); setDateCell(courseSheetRow2.createCell((short) 3), evaluation.getDueDate()); setDateCell(instructorSheetRow2.createCell((short) 3), evaluation.getDueDate()); } // List of groups if (groupIDs.length > 0) { rowCounter++; Row courseSheetRow3 = courseSheet.createRow(rowCounter); Row instructorSheetRow3 = instructorSheet.createRow(rowCounter); Cell courseSheetCellA3 = courseSheetRow3.createCell((short) 0); Cell instructorSheetCellA3 = instructorSheetRow3.createCell((short) 0); // Get the section/site titles setPlainStringCell(courseSheetCellA3, messageLocator.getMessage("reporting.xls.participants", new Object[] { responseAggregator.getCommaSeparatedGroupNames(groupIDs) })); setPlainStringCell(instructorSheetCellA3, messageLocator.getMessage("reporting.xls.participants", new Object[] { responseAggregator.getCommaSeparatedGroupNames(groupIDs) })); } // Column headers (static) rowCounter += 2; short courseSheetHeaderCount = 1; short instructorSheetHeaderCount = 1; Row courseSheetHeaderRow = courseSheet.createRow(rowCounter); Row instructorSheetHeaderRow = instructorSheet.createRow(rowCounter); Cell courseSheetSectionHeaderCell = courseSheetHeaderRow.createCell(courseSheetHeaderCount++); Cell instructorSheetSectionHeaderCell = instructorSheetHeaderRow.createCell(instructorSheetHeaderCount++); if (evaluation.getSectionAwareness()) { courseSheetSectionHeaderCell.setCellValue(messageLocator.getMessage("viewreport.section.header")); instructorSheetSectionHeaderCell.setCellValue(messageLocator.getMessage("viewreport.section.header")); } else { courseSheetSectionHeaderCell.setCellValue(messageLocator.getMessage("viewreport.site.header")); instructorSheetSectionHeaderCell.setCellValue(messageLocator.getMessage("viewreport.site.header")); } courseSheetSectionHeaderCell.setCellStyle(boldHeaderStyle); instructorSheetSectionHeaderCell.setCellStyle(boldHeaderStyle); Cell courseSheetResponseIdHeaderCell = courseSheetHeaderRow.createCell(courseSheetHeaderCount++); Cell instructorSheetResponseIdHeaderCell = instructorSheetHeaderRow .createCell(instructorSheetHeaderCount++); courseSheetResponseIdHeaderCell.setCellValue(messageLocator.getMessage("viewreport.responseID.header")); instructorSheetResponseIdHeaderCell.setCellValue(messageLocator.getMessage("viewreport.responseID.header")); courseSheetResponseIdHeaderCell.setCellStyle(boldHeaderStyle); instructorSheetResponseIdHeaderCell.setCellStyle(boldHeaderStyle); Cell instructorSheetInstructorIdHeaderCell = instructorSheetHeaderRow .createCell(instructorSheetHeaderCount++); instructorSheetInstructorIdHeaderCell .setCellValue(messageLocator.getMessage("viewreport.instructorID.header")); instructorSheetInstructorIdHeaderCell.setCellStyle(boldHeaderStyle); Cell instructorSheetFirstNameHeaderCell = instructorSheetHeaderRow.createCell(instructorSheetHeaderCount++); instructorSheetFirstNameHeaderCell.setCellValue(messageLocator.getMessage("viewreport.firstName.header")); instructorSheetFirstNameHeaderCell.setCellStyle(boldHeaderStyle); Cell instructorSheetLastNameHeaderCell = instructorSheetHeaderRow.createCell(instructorSheetHeaderCount++); instructorSheetLastNameHeaderCell.setCellValue(messageLocator.getMessage("viewreport.lastName.header")); instructorSheetLastNameHeaderCell.setCellStyle(boldHeaderStyle); // Generate dynamic question headers List<String> instructorRelatedQuestions = new ArrayList<>(); for (DataTemplateItem dti : dtiList) { // Skip items that aren't for the current user if (isItemNotForCurrentUser(instructorViewAllResults, currentUserId, evalOwner, dti)) { continue; } // If there's already a header for a specific instructor question, don't list it twice String questionText = commonLogic.makePlainTextFromHTML(dti.templateItem.getItem().getItemText()); if (instructorRelatedQuestions.contains(questionText)) { continue; } // Add the header to the appropriate worksheet Cell questionTextHeaderCell; if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(dti.associateType) || EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(dti.associateType)) { instructorRelatedQuestions.add(questionText); questionTextHeaderCell = instructorSheetHeaderRow.createCell(instructorSheetHeaderCount++); questionTextHeaderCell.setCellStyle(boldHeaderStyle); if (dti.usesComments()) { setPlainStringCell(instructorSheetHeaderRow.createCell(instructorSheetHeaderCount++), messageLocator.getMessage("viewreport.comments.header")) .setCellStyle(italicMiniHeaderStyle); } } else { questionTextHeaderCell = courseSheetHeaderRow.createCell(courseSheetHeaderCount++); questionTextHeaderCell.setCellStyle(boldHeaderStyle); if (dti.usesComments()) { setPlainStringCell(courseSheetHeaderRow.createCell(courseSheetHeaderCount++), messageLocator.getMessage("viewreport.comments.header")) .setCellStyle(italicMiniHeaderStyle); } } setPlainStringCell(questionTextHeaderCell, questionText); } // Parse out the instructor and course related responeses into separate structures List<Long> responseIDs = tidl.getResponseIdsForAnswers(); List<List<String>> courseRelatedResponses = new ArrayList<>(); Map<Long, Map<User, List<EvalAnswer>>> answerMap = new HashMap<>(); for (Long responseID : responseIDs) { // Dump the (course related) data into a list of strings representing a spreadsheet row (so it can be sorted) List<String> row = new ArrayList<>(); String groupID = ""; List<EvalAnswer> answers = tidl.getAnswersByResponseId(responseID); if (answers != null && !answers.isEmpty()) { groupID = answers.get(0).getResponse().getEvalGroupId(); } row.add(SECTION_OR_SITE_COLUMN_NUM, responseAggregator.getCommaSeparatedGroupNames(new String[] { groupID })); row.add(RESPONSE_ID_COLUMN_NUM, responseID.toString()); // Add the response ID to the answer map answerMap.put(responseID, new HashMap<>()); // Loop through the data template items... int questionCounter = 0; for (DataTemplateItem dti : dtiList) { // Skip items that aren't for the current user if (isItemNotForCurrentUser(instructorViewAllResults, currentUserId, evalOwner, dti)) { continue; } // If it's an instructor related item... EvalAnswer answer = dti.getAnswer(responseID); if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(dti.associateType) || EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(dti.associateType)) { // If the answer is NOT null (it would be null for an instructor from a different section than the evaluator) if (answer != null) { // Get the instructor User instructor; try { instructor = userDirectoryService.getUser(answer.getAssociatedId()); } catch (UserNotDefinedException ex) { continue; } // If the answer map has a list of answers for this response and this instructor, add the answer to the list Map<User, List<EvalAnswer>> responseAnswers = answerMap.get(responseID); List<EvalAnswer> instructorAnswers = responseAnswers.get(instructor); if (instructorAnswers != null) { instructorAnswers.add(answer); } // Otherwise, the answer map doesn't have a list of answers for this response and this instructor, // create the list and add the answer to it else { instructorAnswers = new ArrayList<>(); instructorAnswers.add(answer); responseAnswers.put(instructor, instructorAnswers); } } } // If it's a course related item, just add it normally to the course worksheet else { row.add(QUESTION_COMMENTS_COLUMN_START_INDEX_COURSE_SHEET + questionCounter, ""); if (answer != null) { row.set(QUESTION_COMMENTS_COLUMN_START_INDEX_COURSE_SHEET + questionCounter, responseAggregator.formatForSpreadSheet(answer.getTemplateItem(), answer)); } if (dti.usesComments()) { row.add(QUESTION_COMMENTS_COLUMN_START_INDEX_COURSE_SHEET + ++questionCounter, StringUtils.trimToEmpty(answer.getComment())); } questionCounter++; } } // Add the course row data to the list of course data rows courseRelatedResponses.add(row); } // Convert the map structure of instructor responses into a List<List<String>>, representing rows of data List<List<String>> instructorRelatedResponses = new ArrayList<>(); for (Long responseID : answerMap.keySet()) { // Loop through the instructors for the current response for (User instructor : answerMap.get(responseID).keySet()) { // Dump the data into a list of strings representing a spreadsheet row (so it can be sorted) List<String> row = new ArrayList<>(); row.add(SECTION_OR_SITE_COLUMN_NUM, ""); row.add(RESPONSE_ID_COLUMN_NUM, responseID.toString()); row.add(INSTRUCTOR_ID_COLUMN_NUM, ""); row.add(INSTRUCTOR_FIRST_NAME_COLUMN_NUM, ""); row.add(INSTRUCTOR_LAST_NAME_COLUMN_NUM, ""); if (instructor != null) { row.set(INSTRUCTOR_ID_COLUMN_NUM, instructor.getDisplayId()); row.set(INSTRUCTOR_FIRST_NAME_COLUMN_NUM, instructor.getFirstName()); row.set(INSTRUCTOR_LAST_NAME_COLUMN_NUM, instructor.getLastName()); } int questionCounter = 0; for (EvalAnswer answer : answerMap.get(responseID).get(instructor)) { row.set(SECTION_OR_SITE_COLUMN_NUM, responseAggregator .getCommaSeparatedGroupNames(new String[] { answer.getResponse().getEvalGroupId() })); row.add(QUESTION_COMMENTS_COLUMN_START_INDEX_INSTRUCTOR_SHEET + questionCounter, ""); row.set(QUESTION_COMMENTS_COLUMN_START_INDEX_INSTRUCTOR_SHEET + questionCounter, responseAggregator.formatForSpreadSheet(answer.getTemplateItem(), answer)); String comment = StringUtils.trimToEmpty(answer.getComment()); if (!comment.isEmpty()) { row.add(QUESTION_COMMENTS_COLUMN_START_INDEX_INSTRUCTOR_SHEET + ++questionCounter, (StringUtils.trimToEmpty(answer.getComment()))); } questionCounter++; } // Add the row to the list of rows instructorRelatedResponses.add(row); } } // Sort the row data lists SortBySectionOrSiteComparator sorter = new SortBySectionOrSiteComparator(); Collections.sort(instructorRelatedResponses, sorter); Collections.sort(courseRelatedResponses, sorter); // Output the sorted course related data into the course spreadsheet rowCounter = 0; for (List<String> row : courseRelatedResponses) { // Course sheet answer row, index cell short columnCounter = SECTION_OR_SITE_COLUMN_NUM; Row courseSheetAnswerRow = courseSheet.createRow(FIRST_ANSWER_ROW + rowCounter); Cell courseAnswerIndexCell = courseSheetAnswerRow.createCell(columnCounter++); courseAnswerIndexCell.setCellValue(rowCounter + 1); courseAnswerIndexCell.setCellStyle(boldHeaderStyle); // Course sheet section cell, response ID cell Cell courseSheetSectionCell = courseSheetAnswerRow.createCell(columnCounter++); Cell courseSheetResponseIdCell = courseSheetAnswerRow.createCell(columnCounter++); courseSheetSectionCell.setCellValue(row.get(SECTION_OR_SITE_COLUMN_NUM)); courseSheetResponseIdCell.setCellValue(Integer.parseInt(row.get(RESPONSE_ID_COLUMN_NUM))); // Responses and comments for (int i = QUESTION_COMMENTS_COLUMN_START_INDEX_COURSE_SHEET; i < row.size(); i++) { setPlainStringCell(courseSheetAnswerRow.createCell(columnCounter++), row.get(i)); } // Increment the row counter rowCounter++; } // Output the sorted instructor related data into the instructor spreadsheet rowCounter = 0; for (List<String> row : instructorRelatedResponses) { // Answer row, index cell short columnCounter = SECTION_OR_SITE_COLUMN_NUM; Row instructorSheetAnswerRow = instructorSheet.createRow(FIRST_ANSWER_ROW + rowCounter); Cell instructorAnswerIndexCell = instructorSheetAnswerRow.createCell(columnCounter++); instructorAnswerIndexCell.setCellValue(rowCounter + 1); instructorAnswerIndexCell.setCellStyle(boldHeaderStyle); // Section cell, response ID cell Cell instructorSheetSectionCell = instructorSheetAnswerRow.createCell(columnCounter++); Cell instructorSheetResponseIdCell = instructorSheetAnswerRow.createCell(columnCounter++); instructorSheetSectionCell.setCellValue(row.get(SECTION_OR_SITE_COLUMN_NUM)); instructorSheetResponseIdCell.setCellValue(Integer.parseInt(row.get(RESPONSE_ID_COLUMN_NUM))); // Instructor ID, first name, last name cells Cell instructorIdCell = instructorSheetAnswerRow.createCell(columnCounter++); Cell instructorFirstNameCell = instructorSheetAnswerRow.createCell(columnCounter++); Cell instructorLastNameCell = instructorSheetAnswerRow.createCell(columnCounter++); instructorIdCell.setCellValue(row.get(INSTRUCTOR_ID_COLUMN_NUM)); instructorFirstNameCell.setCellValue(row.get(INSTRUCTOR_FIRST_NAME_COLUMN_NUM)); instructorLastNameCell.setCellValue(row.get(INSTRUCTOR_LAST_NAME_COLUMN_NUM)); // Responses and comments for (int i = QUESTION_COMMENTS_COLUMN_START_INDEX_INSTRUCTOR_SHEET; i < row.size(); i++) { setPlainStringCell(instructorSheetAnswerRow.createCell(columnCounter++), row.get(i)); } // Increment the row counter rowCounter++; } // Dump the output to the response stream try { wb.write(outputStream); } catch (IOException e) { throw UniversalRuntimeException.accumulate(e, "Could not get Writer to dump output to xls"); } }
From source file:org.sakaiproject.evaluation.tool.reporting.XLSReportExporter.java
License:Educational Community License
public void buildReport(EvalEvaluation evaluation, String[] groupIds, String evaluateeId, OutputStream outputStream, boolean newReportStyle) { /*//from www . jav a2 s. c o m * Logic for creating this view 1) make tidl 2) get DTIs for this eval from tidl 3) use DTIs * to make the headers 4) get responseIds from tidl 5) loop over response ids 6) loop over * DTIs 7) check answersmap for an answer, if there put in cell, if missing, insert blank 8) * done */ //Make sure responseAggregator is using this messageLocator responseAggregator.setMessageLocator(messageLocator); // Determine which report style to use; normal or section based if (newReportStyle) { buildReportSectionAware(evaluation, groupIds, outputStream); } else { Boolean instructorViewAllResults = (boolean) evaluation.getInstructorViewAllResults(); String currentUserId = commonLogic.getCurrentUserId(); String evalOwner = evaluation.getOwner(); boolean isCurrentUserAdmin = commonLogic.isUserAdmin(currentUserId); // 1 Make TIDL TemplateItemDataList tidl = getEvalTIDL(evaluation, groupIds); // 2: get DTIs for this eval from tidl List<DataTemplateItem> dtiList = tidl.getFlatListOfDataTemplateItems(true); Workbook wb = new XSSFWorkbook(); creationHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet(messageLocator.getMessage("reporting.xls.sheetname")); // Title Style Font font = wb.createFont(); font.setFontHeightInPoints((short) 12); font.setBold(true); CellStyle mainTitleStyle = wb.createCellStyle(); mainTitleStyle.setFont(font); // Bold header style font = wb.createFont(); font.setFontHeightInPoints((short) 10); font.setBold(true); CellStyle boldHeaderStyle = wb.createCellStyle(); boldHeaderStyle.setFont(font); // Italic meta header style font = wb.createFont(); font.setFontHeightInPoints((short) 10); font.setItalic(true); CellStyle italicMiniHeaderStyle = wb.createCellStyle(); italicMiniHeaderStyle.setFont(font); // Date meta Style dateCellStyle = wb.createCellStyle(); // TODO FIXME HELPME To properly // String dateCellFormat = ((SimpleDateFormat)DateFormat.getDateInstance(DateFormat.MEDIUM, // localeGetter.get())).toLocalizedPattern(); // http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDataFormat.html dateCellStyle.setDataFormat((short) 0x16); // Evaluation Title Row row1 = sheet.createRow(0); Cell cellA1 = row1.createCell((short) 0); setPlainStringCell(cellA1, evaluation.getTitle()); cellA1.setCellStyle(mainTitleStyle); // calculate the response rate // int responsesCount = deliveryService.countResponses(evaluation.getId(), null, true); int responsesCount = evaluationService.countResponses(null, new Long[] { evaluation.getId() }, groupIds, null); int enrollmentsCount = evaluationService.countParticipantsForEval(evaluation.getId(), groupIds); Row row2 = sheet.createRow(1); Cell cellA2 = row2.createCell((short) 0); cellA2.setCellStyle(boldHeaderStyle); setPlainStringCell(cellA2, EvalUtils.makeResponseRateStringFromCounts(responsesCount, enrollmentsCount)); // dates setPlainStringCell(row1.createCell((short) 2), messageLocator.getMessage("evalsettings.start.date.header")); setDateCell(row2.createCell((short) 2), evaluation.getStartDate()); if (evaluation.getDueDate() != null) { setPlainStringCell(row1.createCell((short) 3), messageLocator.getMessage("evalsettings.due.date.header")); setDateCell(row2.createCell((short) 3), evaluation.getDueDate()); } // add in list of groups if (groupIds.length > 0) { Row row3 = sheet.createRow(2); Cell cellA3 = row3.createCell((short) 0); setPlainStringCell(cellA3, messageLocator.getMessage("reporting.xls.participants", new Object[] { responseAggregator.getCommaSeparatedGroupNames(groupIds) })); } // 3 use DTIs to make the headers Row questionCatRow = sheet.createRow(QUESTION_CAT_ROW); Row questionTypeRow = sheet.createRow(QUESTION_TYPE_ROW); Row questionTextRow = sheet.createRow(QUESTION_TEXT_ROW); short headerCount = 1; for (DataTemplateItem dti : dtiList) { if (!instructorViewAllResults // If the eval is so configured, && !isCurrentUserAdmin // and currentUser is not an admin && !currentUserId.equals(evalOwner) // and currentUser is not the eval creator && !EvalConstants.ITEM_CATEGORY_COURSE.equals(dti.associateType) && !currentUserId.equals(commonLogic.getEvalUserById(dti.associateId).userId)) { // skip items that aren't for the current user continue; } Cell cell = questionTypeRow.createCell(headerCount); setPlainStringCell(cell, responseAggregator.getHeaderLabelForItemType(dti.getTemplateItemType())); cell.setCellStyle(italicMiniHeaderStyle); Cell questionText = questionTextRow.createCell(headerCount); setPlainStringCell(questionText, commonLogic.makePlainTextFromHTML(dti.templateItem.getItem().getItemText())); Cell questionCat = questionCatRow.createCell(headerCount); if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(dti.associateType)) { EvalUser user = commonLogic.getEvalUserById(dti.associateId); String instructorMsg = messageLocator.getMessage("reporting.spreadsheet.instructor", new Object[] { user.displayName }); setPlainStringCell(questionCat, instructorMsg); } else if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(dti.associateType)) { EvalUser user = commonLogic.getEvalUserById(dti.associateId); String assistantMsg = messageLocator.getMessage("reporting.spreadsheet.ta", new Object[] { user.displayName }); setPlainStringCell(questionCat, assistantMsg); } else if (EvalConstants.ITEM_CATEGORY_COURSE.equals(dti.associateType)) { setPlainStringCell(questionCat, messageLocator.getMessage("reporting.spreadsheet.course")); } else { setPlainStringCell(questionCat, messageLocator.getMessage("unknown.caps")); } headerCount++; if (dti.usesComments()) { // add an extra column for comments setPlainStringCell(questionTypeRow.createCell(headerCount), messageLocator.getMessage("viewreport.comments.header")) .setCellStyle(italicMiniHeaderStyle); headerCount++; } } // 4) get responseIds from tidl List<Long> responseIds = tidl.getResponseIdsForAnswers(); // 5) loop over response ids short responseIdCounter = 0; for (Long responseId : responseIds) { Row row = sheet.createRow(responseIdCounter + FIRST_ANSWER_ROW); Cell indexCell = row.createCell((short) 0); indexCell.setCellValue(responseIdCounter + 1); indexCell.setCellStyle(boldHeaderStyle); // 6) loop over DTIs short dtiCounter = 1; for (DataTemplateItem dti : dtiList) { if (!instructorViewAllResults // If the eval is so configured, && !isCurrentUserAdmin // and currentUser is not an admin && !currentUserId.equals(evalOwner) // and currentUser is not the eval creator && !EvalConstants.ITEM_CATEGORY_COURSE.equals(dti.associateType) && !currentUserId.equals(commonLogic.getEvalUserById(dti.associateId).userId)) { //skip instructor items that aren't for the current user continue; } // 7) check answersmap for an answer, if there put in cell, if missing, insert blank EvalAnswer answer = dti.getAnswer(responseId); Cell responseCell = row.createCell(dtiCounter); // In Eval, users can leave questions blank, in which case this will be null if (answer != null) { setPlainStringCell(responseCell, responseAggregator.formatForSpreadSheet(answer.getTemplateItem(), answer)); } if (dti.usesComments()) { // put comment in the extra column dtiCounter++; setPlainStringCell(row.createCell(dtiCounter), (answer == null || EvalUtils.isBlank(answer.getComment())) ? "" : answer.getComment()); } dtiCounter++; } responseIdCounter++; } // dump the output to the response stream try { wb.write(outputStream); } catch (IOException e) { throw UniversalRuntimeException.accumulate(e, "Could not get Writer to dump output to xls"); } } }
From source file:org.unitime.timetable.export.XLSPrinter.java
License:Apache License
protected Font getFont(boolean bold, boolean italic, boolean underline, Color c) { Short color = null;/* www .j av a 2 s . c o m*/ if (c == null) c = Color.BLACK; if (c != null) { String colorId = Integer.toHexString(c.getRGB()); color = iColors.get(colorId); if (color == null) { HSSFPalette palette = ((HSSFWorkbook) iWorkbook).getCustomPalette(); HSSFColor clr = palette.findSimilarColor(c.getRed(), c.getGreen(), c.getBlue()); color = (clr == null ? IndexedColors.BLACK.getIndex() : clr.getIndex()); iColors.put(colorId, color); } } String fontId = (bold ? "b" : "") + (italic ? "i" : "") + (underline ? "u" : "") + (color == null ? "" : color); Font font = iFonts.get(fontId); if (font == null) { font = iWorkbook.createFont(); font.setBold(bold); font.setItalic(italic); font.setUnderline(underline ? Font.U_SINGLE : Font.U_NONE); font.setColor(color); font.setFontHeightInPoints((short) 10); font.setFontName("Arial"); iFonts.put(fontId, font); } return font; }
From source file:org.zafritech.zidingorms.io.excel.ExcelFunctions.java
private static Map<String, CellStyle> createStyles(Workbook wb) { Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); CreationHelper creationHelper = wb.getCreationHelper(); CellStyle style;/*w ww. ja v a 2 s . c o m*/ // Header Font Font headerFont = wb.createFont(); headerFont.setFontHeightInPoints((short) 12); headerFont.setBold(true); headerFont.setColor(IndexedColors.WHITE.getIndex()); // Header Left Aligned Style style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setFont(headerFont); style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); styles.put("HeaderLeftAlign", style); // Header Center Aligned Style style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setFont(headerFont); style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); styles.put("HeaderCenterAlign", style); // Body Left Aligned Style style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setVerticalAlignment(VerticalAlignment.TOP); styles.put("BodyLeftAlign", style); // Body Center Aligned Style style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.TOP); styles.put("BodyCenterAlign", style); // Body Left Aligned WrapText Style style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setVerticalAlignment(VerticalAlignment.TOP); style.setWrapText(true); styles.put("BodyLeftAlignWrapText", style); // Body Left Aligned Date Format Style style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setVerticalAlignment(VerticalAlignment.TOP); style.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss")); styles.put("BodyLeftAlignDate", style); // Body Center Aligned Date Format Style style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.TOP); style.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss")); styles.put("BodyCenterAlignDate", style); return styles; }
From source file:paysheets.PaySheetFormatter.java
public static void addTitleRow(HSSFWorkbook workbook) { workbook.createSheet("Sheet 1"); // Each pay sheet only uses the first sheet HSSFSheet sheet = workbook.getSheetAt(0); setDefaultColumnWidth(sheet);//from w w w . ja v a 2s . c o m HSSFRow row; HSSFCell cell; // Create a font and set its attributes Font font = workbook.createFont(); font.setFontHeightInPoints((short) 11); // Set the color to black (constant COLOR_NORMAL) font.setColor(Font.COLOR_NORMAL); font.setBold(true); // Create a cell style and set its properties CellStyle cs = workbook.createCellStyle(); // Set the data format to the built in text format cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("text")); // Set the cell style to use the font created previously cs.setFont(font); // Create the first title row row = sheet.createRow(0); // Use the default row height (-1) is sheet default row.setHeight((short) -1); // Add the first title row's 6 cells for (int cellNum = 0; cellNum < 6; cellNum++) { cell = row.createCell(cellNum); cell.setCellStyle(cs); } // Populate first row's values cell = row.getCell(PaySheet.DATE_INDEX); cell.setCellValue("DATE"); cell = row.getCell(PaySheet.CUST_INDEX); cell.setCellValue("CUSTOMER"); cell = row.getCell(PaySheet.PAY_INDEX); cell.setCellValue("PAY"); cell = row.getCell(PaySheet.NONSERIAL_INDEX); cell.setCellValue("EQUIPMENT"); cell = row.getCell(PaySheet.SERIAL_INDEX); cell.setCellValue("SERIALIZED"); cell = row.getCell(PaySheet.SHS_INDEX); cell.setCellValue("SHS"); // Create second title row row = sheet.createRow(1); row.setHeight((short) -1); // Add the cells to the row for (int cellNum = 0; cellNum < 3; cellNum++) { cell = row.createCell(cellNum); cell.setCellStyle(cs); } // Populate the second title row's values cell = row.getCell(PaySheet.WO_INDEX); cell.setCellValue("WORK ORDER"); cell = row.getCell(PaySheet.TYPE_INDEX); cell.setCellValue("TYPE"); cell = row.getCell(PaySheet.LEP_INDEX); cell.setCellValue("LEP"); // Add thick border around title row addJobBorder(workbook, 0); }
From source file:paysheets.PaySheetFormatter.java
public static void addJobFormatting(HSSFWorkbook workbook, int rowIndex) { HSSFSheet sheet = workbook.getSheetAt(0); HSSFRow row;/* w w w . j a v a 2s.c o m*/ HSSFCell cell; Font font = workbook.createFont(); font.setBold(false); font.setFontHeightInPoints((short) 10); font.setColor(Font.COLOR_NORMAL); // Create a cell style for general text CellStyle generalStyle = workbook.createCellStyle(); generalStyle.setFont(font); generalStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text")); // Create a cell style for dates CellStyle dateStyle = workbook.createCellStyle(); dateStyle.setFont(font); // Set the cell data format to date (0xe) is the built in format dateStyle.setDataFormat((short) 0xe); dateStyle.setAlignment(CellStyle.ALIGN_LEFT); // Create a new row at the given index row = sheet.createRow(rowIndex); // Format the first row for the new job for (int cellNum = 0; cellNum < 6; cellNum++) { cell = row.createCell(cellNum); // Only the first cell uses the date style if (cellNum > 0) { cell.setCellStyle(generalStyle); } else { cell.setCellStyle(dateStyle); } } // Create second row for the new Job at rowIndex + 1 row = sheet.createRow(rowIndex + 1); for (int cellNum = 0; cellNum < 3; cellNum++) { cell = row.createCell(cellNum); cell.setCellStyle(generalStyle); } }
From source file:pl.softech.knf.ofe.opf.members.xls.export.XlsMembersWritter.java
License:Apache License
private Font createHeaderFont(final Workbook wb, final short size) { final Font font = wb.createFont(); font.setFontHeightInPoints(size);// ww w . j a va2s. c o m font.setFontName("Arial"); font.setBold(true); return font; }
From source file:pruebaimportarexcel.excel.ExcelUtils.java
/** * Devuelve el CellStyle indicado para las celdas de cabecera de la tabla * * @return/*from ww w . j a va2 s.co m*/ */ public CellStyle GetTitleStyle() { if (titleStyle == null) { titleStyle = wb.createCellStyle(); Font fuenteTitle = wb.createFont(); fuenteTitle.setBold(true); titleStyle.setFont(fuenteTitle); titleStyle.setAlignment(CellStyle.ALIGN_CENTER); titleStyle.setBorderBottom(CellStyle.BORDER_MEDIUM); } return titleStyle; }