List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook createSheet
@Override
public XSSFSheet createSheet(String sheetname)
From source file:org.alfresco.bm.report.XLSXReporter.java
License:Open Source License
/** * Create a 'Summary' sheet containing the table of averages *//*from w ww .jav a 2 s. c om*/ private void createSummarySheet(XSSFWorkbook workbook) throws IOException, NotFoundException { DBObject testRunObj = getTestService().getTestRunMetadata(test, run); // Create the sheet XSSFSheet sheet = workbook.createSheet("Summary"); // Create the fonts we need Font fontBold = workbook.createFont(); fontBold.setBoldweight(Font.BOLDWEIGHT_BOLD); // Create the styles we need XSSFCellStyle summaryDataStyle = sheet.getWorkbook().createCellStyle(); summaryDataStyle.setAlignment(HorizontalAlignment.RIGHT); XSSFCellStyle headerStyle = sheet.getWorkbook().createCellStyle(); headerStyle.setAlignment(HorizontalAlignment.RIGHT); headerStyle.setFont(fontBold); XSSFRow row = null; int rowCount = 0; row = sheet.createRow(rowCount++); { row.getCell(0).setCellValue("Name:"); row.getCell(0).setCellStyle(headerStyle); row.getCell(1).setCellValue(title); row.getCell(1).setCellStyle(summaryDataStyle); } row = sheet.createRow(rowCount++); { String description = (String) testRunObj.get(FIELD_DESCRIPTION); description = description == null ? "" : description; row.getCell(0).setCellValue("Description:"); row.getCell(0).setCellStyle(headerStyle); row.getCell(1).setCellValue(description); row.getCell(1).setCellStyle(summaryDataStyle); } row = sheet.createRow(rowCount++); { row.getCell(0).setCellValue("Progress (%):"); row.getCell(0).setCellStyle(headerStyle); Double progress = (Double) testRunObj.get(FIELD_PROGRESS); progress = progress == null ? 0.0 : progress; row.getCell(1).setCellValue(progress * 100); row.getCell(1).setCellType(XSSFCell.CELL_TYPE_NUMERIC); row.getCell(1).setCellStyle(summaryDataStyle); } row = sheet.createRow(rowCount++); { row.getCell(0).setCellValue("State:"); row.getCell(0).setCellStyle(headerStyle); String state = (String) testRunObj.get(FIELD_STATE); if (state != null) { row.getCell(1).setCellValue(state); row.getCell(1).setCellStyle(summaryDataStyle); } } row = sheet.createRow(rowCount++); { row.getCell(0).setCellValue("Started:"); row.getCell(0).setCellStyle(headerStyle); Long time = (Long) testRunObj.get(FIELD_STARTED); if (time > 0) { row.getCell(1).setCellValue(FastDateFormat .getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM).format(time)); row.getCell(1).setCellStyle(summaryDataStyle); } } row = sheet.createRow(rowCount++); { row.getCell(0).setCellValue("Finished:"); row.getCell(0).setCellStyle(headerStyle); Long time = (Long) testRunObj.get(FIELD_COMPLETED); if (time > 0) { row.getCell(1).setCellValue(FastDateFormat .getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM).format(time)); row.getCell(1).setCellStyle(summaryDataStyle); } } row = sheet.createRow(rowCount++); { row.getCell(0).setCellValue("Duration:"); row.getCell(0).setCellStyle(headerStyle); Long time = (Long) testRunObj.get(FIELD_DURATION); if (time > 0) { row.getCell(1).setCellValue(DurationFormatUtils.formatDurationHMS(time)); row.getCell(1).setCellStyle(summaryDataStyle); } } rowCount++; rowCount++; // Create a header row row = sheet.createRow(rowCount++); // Header row String[] headers = new String[] { "Event Name", "Total Count", "Success Count", "Failure Count", "Success Rate (%)", "Min (ms)", "Max (ms)", "Arithmetic Mean (ms)", "Standard Deviation (ms)" }; int columnCount = 0; for (String header : headers) { XSSFCell cell = row.getCell(columnCount++); cell.setCellStyle(headerStyle); cell.setCellValue(header); } // Grab results and output them columnCount = 0; TreeMap<String, ResultSummary> summaries = collateResults(true); for (Map.Entry<String, ResultSummary> entry : summaries.entrySet()) { // Reset column count columnCount = 0; row = sheet.createRow(rowCount++); String eventName = entry.getKey(); ResultSummary summary = entry.getValue(); SummaryStatistics statsSuccess = summary.getStats(true); SummaryStatistics statsFail = summary.getStats(false); // Event Name row.getCell(columnCount++).setCellValue(eventName); // Total Count row.getCell(columnCount++).setCellValue(summary.getTotalResults()); // Success Count row.getCell(columnCount++).setCellValue(statsSuccess.getN()); // Failure Count row.getCell(columnCount++).setCellValue(statsFail.getN()); // Success Rate (%) row.getCell(columnCount++).setCellValue(summary.getSuccessPercentage()); // Min (ms) row.getCell(columnCount++).setCellValue((long) statsSuccess.getMin()); // Max (ms) row.getCell(columnCount++).setCellValue((long) statsSuccess.getMax()); // Arithmetic Mean (ms) row.getCell(columnCount++).setCellValue((long) statsSuccess.getMean()); // Standard Deviation (ms) row.getCell(columnCount++).setCellValue((long) statsSuccess.getStandardDeviation()); } // Auto-size the columns for (int i = 0; i < 10; i++) { sheet.autoSizeColumn(i); } sheet.setColumnWidth(1, 5120); // Printing PrintSetup ps = sheet.getPrintSetup(); sheet.setAutobreaks(true); ps.setFitWidth((short) 1); ps.setLandscape(true); // Header and footer sheet.getHeader().setCenter(title); }
From source file:org.alfresco.bm.report.XLSXReporter.java
License:Open Source License
private void createPropertiesSheet(XSSFWorkbook workbook) throws IOException, NotFoundException { DBObject testRunObj;//from w ww . ja v a 2 s . com try { testRunObj = services.getTestDAO().getTestRun(test, run, true); } catch (ObjectNotFoundException e) { logger.error("Test run not found!", e); return; } // Ensure we don't leak passwords testRunObj = AbstractRestResource.maskValues(testRunObj); BasicDBList propertiesList = (BasicDBList) testRunObj.get(FIELD_PROPERTIES); if (propertiesList == null) { logger.error("Properties not found!"); return; } // Order the properties, nicely TreeMap<String, DBObject> properties = new TreeMap<String, DBObject>(); for (Object propertyObj : propertiesList) { DBObject property = (DBObject) propertyObj; String key = (String) property.get(FIELD_NAME); properties.put(key, property); } XSSFSheet sheet = workbook.createSheet("Properties"); // Create the fonts we need Font fontBold = workbook.createFont(); fontBold.setBoldweight(Font.BOLDWEIGHT_BOLD); // Create the styles we need XSSFCellStyle propertyStyle = sheet.getWorkbook().createCellStyle(); propertyStyle.setAlignment(HorizontalAlignment.RIGHT); propertyStyle.setWrapText(true); XSSFCellStyle headerStyle = sheet.getWorkbook().createCellStyle(); headerStyle.setAlignment(HorizontalAlignment.RIGHT); headerStyle.setFont(fontBold); XSSFRow row = null; int rowCount = 0; XSSFCell cell = null; int cellCount = 0; row = sheet.createRow(rowCount++); cell = row.createCell(cellCount++); { cell.setCellValue("Property"); cell.setCellStyle(headerStyle); } cell = row.createCell(cellCount++); { cell.setCellValue("Value"); cell.setCellStyle(headerStyle); } cell = row.createCell(cellCount++); { cell.setCellValue("Origin"); cell.setCellStyle(headerStyle); } cellCount = 0; // Iterate all the properties for the test run for (Map.Entry<String, DBObject> entry : properties.entrySet()) { DBObject property = entry.getValue(); String key = (String) property.get(FIELD_NAME); String value = (String) property.get(FIELD_VALUE); String origin = (String) property.get(FIELD_ORIGIN); row = sheet.createRow(rowCount++); cell = row.createCell(cellCount++); { cell.setCellValue(key); cell.setCellStyle(propertyStyle); } cell = row.createCell(cellCount++); { cell.setCellValue(value); cell.setCellStyle(propertyStyle); } cell = row.createCell(cellCount++); { cell.setCellValue(origin); cell.setCellStyle(propertyStyle); } // Back to first column cellCount = 0; } // Size the columns sheet.autoSizeColumn(0); sheet.setColumnWidth(1, 15360); sheet.autoSizeColumn(2); // Printing PrintSetup ps = sheet.getPrintSetup(); sheet.setAutobreaks(true); ps.setFitWidth((short) 1); ps.setLandscape(true); // Header and footer sheet.getHeader().setCenter(title); }
From source file:org.alfresco.bm.report.XLSXReporter.java
License:Open Source License
private void createEventSheets(final XSSFWorkbook workbook) { // Create the fonts we need Font fontBold = workbook.createFont(); fontBold.setBoldweight(Font.BOLDWEIGHT_BOLD); // Create the styles we need CreationHelper helper = workbook.getCreationHelper(); final XSSFCellStyle dataStyle = workbook.createCellStyle(); dataStyle.setAlignment(HorizontalAlignment.RIGHT); final XSSFCellStyle headerStyle = workbook.createCellStyle(); headerStyle.setAlignment(HorizontalAlignment.RIGHT); headerStyle.setFont(fontBold);//from ww w . java 2 s . c o m final XSSFCellStyle dateStyle = workbook.createCellStyle(); dateStyle.setDataFormat(helper.createDataFormat().getFormat("HH:mm:ss")); // Calculate a good window size ResultService resultService = getResultService(); EventRecord firstResult = resultService.getFirstResult(); EventRecord lastResult = resultService.getLastResult(); if (firstResult == null || lastResult == null) { return; } long start = firstResult.getStartTime(); long end = lastResult.getStartTime(); long windowSize = AbstractEventReporter.getWindowSize(start, end, 100); // Well-known window sizes // Keep track of sheets by event name. Note that XLSX truncates sheets to 31 chars, so use 28 chars and ~01, ~02 final Map<String, String> sheetNames = new HashMap<String, String>(31); final Map<String, XSSFSheet> sheets = new HashMap<String, XSSFSheet>(31); final Map<String, AtomicInteger> rowNums = new HashMap<String, AtomicInteger>(31); ResultHandler handler = new ResultHandler() { @Override public boolean processResult(long fromTime, long toTime, Map<String, DescriptiveStatistics> statsByEventName, Map<String, Integer> failuresByEventName) throws Throwable { // Get or create a sheet for each event for (String eventName : statsByEventName.keySet()) { // What sheet name to we use? String sheetName = sheetNames.get(eventName); if (sheetName == null) { sheetName = eventName; if (eventName.length() > 28) { int counter = 1; // Find a sheet name not in use while (true) { sheetName = eventName.substring(0, 28); sheetName = String.format("%s~%02d", sheetName, counter); // Have we used this, yet? if (sheets.containsKey(sheetName)) { // Yes, we have used it. counter++; continue; } // This is unique break; } } sheetNames.put(eventName, sheetName); } // Get and create the sheet, if necessary XSSFSheet sheet = sheets.get(sheetName); if (sheet == null) { // Create try { sheet = workbook.createSheet(sheetName); sheets.put(sheetName, sheet); sheet.getHeader().setCenter(title + " - " + eventName); sheet.getPrintSetup().setFitWidth((short) 1); sheet.getPrintSetup().setLandscape(true); } catch (Exception e) { logger.error("Unable to create workbook sheet for event: " + eventName, e); continue; } // Intro XSSFCell cell = sheet.createRow(0).createCell(0); cell.setCellValue(title + " - " + eventName + ":"); cell.setCellStyle(headerStyle); // Headings XSSFRow row = sheet.createRow(1); cell = row.createCell(0); cell.setCellStyle(headerStyle); cell.setCellValue("time"); cell = row.createCell(1); cell.setCellStyle(headerStyle); cell.setCellValue("mean"); cell = row.createCell(2); cell.setCellStyle(headerStyle); cell.setCellValue("min"); cell = row.createCell(3); cell.setCellStyle(headerStyle); cell.setCellValue("max"); cell = row.createCell(4); cell.setCellStyle(headerStyle); cell.setCellValue("stdDev"); cell = row.createCell(5); cell.setCellStyle(headerStyle); cell.setCellValue("num"); cell = row.createCell(6); cell.setCellStyle(headerStyle); cell.setCellValue("numPerSec"); cell = row.createCell(7); cell.setCellStyle(headerStyle); cell.setCellValue("fail"); cell = row.createCell(8); cell.setCellStyle(headerStyle); cell.setCellValue("failPerSec"); // Size the columns sheet.autoSizeColumn(0); sheet.autoSizeColumn(1); sheet.autoSizeColumn(2); sheet.autoSizeColumn(3); sheet.autoSizeColumn(4); sheet.autoSizeColumn(5); sheet.autoSizeColumn(6); sheet.autoSizeColumn(7); sheet.autoSizeColumn(8); } AtomicInteger rowNum = rowNums.get(eventName); if (rowNum == null) { rowNum = new AtomicInteger(2); rowNums.put(eventName, rowNum); } DescriptiveStatistics stats = statsByEventName.get(eventName); Integer failures = failuresByEventName.get(eventName); double numPerSec = (double) stats.getN() / ((double) (toTime - fromTime) / 1000.0); double failuresPerSec = (double) failures / ((double) (toTime - fromTime) / 1000.0); XSSFRow row = sheet.createRow(rowNum.getAndIncrement()); XSSFCell cell; cell = row.createCell(0, Cell.CELL_TYPE_NUMERIC); cell.setCellStyle(dateStyle); cell.setCellValue(new Date(toTime)); cell = row.createCell(5, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(stats.getN()); cell = row.createCell(6, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(numPerSec); cell = row.createCell(7, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(failures); cell = row.createCell(8, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(failuresPerSec); // Leave out values if there is no mean if (Double.isNaN(stats.getMean())) { continue; } cell = row.createCell(1, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(stats.getMean()); cell = row.createCell(2, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(stats.getMin()); cell = row.createCell(3, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(stats.getMax()); cell = row.createCell(4, Cell.CELL_TYPE_NUMERIC); cell.setCellValue(stats.getStandardDeviation()); } return true; } }; resultService.getResults(handler, start, windowSize, windowSize, false); // Create charts in the sheets for (String eventName : sheetNames.keySet()) { // Get the sheet name String sheetName = sheetNames.get(eventName); if (sheetName == null) { logger.error("Did not find sheet for event: " + eventName); continue; } // Get the sheet XSSFSheet sheet = sheets.get(sheetName); if (sheet == null) { logger.error("Did not find sheet for name: " + sheetName); continue; } // What row did we get up to AtomicInteger rowNum = rowNums.get(eventName); if (rowNum == null) { logger.error("Did not find row number for event: " + sheetName); continue; } // This axis is common to both charts ChartDataSource<Number> xTime = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, rowNum.intValue() - 1, 0, 0)); // Graph of event times XSSFDrawing drawingTimes = sheet.createDrawingPatriarch(); ClientAnchor anchorTimes = drawingTimes.createAnchor(0, 0, 0, 0, 0, 5, 15, 25); Chart chartTimes = drawingTimes.createChart(anchorTimes); ChartLegend legendTimes = chartTimes.getOrCreateLegend(); legendTimes.setPosition(LegendPosition.BOTTOM); LineChartData chartDataTimes = chartTimes.getChartDataFactory().createLineChartData(); ChartAxis bottomAxisTimes = chartTimes.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); bottomAxisTimes.setNumberFormat("#,##0;-#,##0"); ValueAxis leftAxisTimes = chartTimes.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); // Mean ChartDataSource<Number> yMean = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, rowNum.intValue() - 1, 1, 1)); LineChartSeries yMeanSerie = chartDataTimes.addSeries(xTime, yMean); yMeanSerie.setTitle(title + " - " + eventName + ": Mean (ms)"); // Std Dev ChartDataSource<Number> yStdDev = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, rowNum.intValue() - 1, 4, 4)); LineChartSeries yStdDevSerie = chartDataTimes.addSeries(xTime, yStdDev); yStdDevSerie.setTitle(title + " - " + eventName + ": Standard Deviation (ms)"); // Plot event times chartTimes.plot(chartDataTimes, bottomAxisTimes, leftAxisTimes); // Graph of event volumes // Graph of event times XSSFDrawing drawingVolumes = sheet.createDrawingPatriarch(); ClientAnchor anchorVolumes = drawingVolumes.createAnchor(0, 0, 0, 0, 0, 25, 15, 35); Chart chartVolumes = drawingVolumes.createChart(anchorVolumes); ChartLegend legendVolumes = chartVolumes.getOrCreateLegend(); legendVolumes.setPosition(LegendPosition.BOTTOM); LineChartData chartDataVolumes = chartVolumes.getChartDataFactory().createLineChartData(); ChartAxis bottomAxisVolumes = chartVolumes.getChartAxisFactory() .createCategoryAxis(AxisPosition.BOTTOM); bottomAxisVolumes.setNumberFormat("#,##0;-#,##0"); ValueAxis leftAxisVolumes = chartVolumes.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); // Number per second ChartDataSource<Number> yNumPerSec = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, rowNum.intValue() - 1, 6, 6)); LineChartSeries yNumPerSecSerie = chartDataVolumes.addSeries(xTime, yNumPerSec); yNumPerSecSerie.setTitle(title + " - " + eventName + ": Events per Second"); // Failures per second ChartDataSource<Number> yFailPerSec = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, rowNum.intValue() - 1, 8, 8)); LineChartSeries yFailPerSecSerie = chartDataVolumes.addSeries(xTime, yFailPerSec); yFailPerSecSerie.setTitle(title + " - " + eventName + ": Failures per Second"); // Plot volumes chartVolumes.plot(chartDataVolumes, bottomAxisVolumes, leftAxisVolumes); } }
From source file:org.apache.fineract.accounting.closure.storeglaccountbalance.service.GLClosureJournalEntryBalanceReadPlatformServiceImpl.java
License:Apache License
/** * Create the excel file with the balance report data * /* w w w . j a v a 2 s .c o m*/ * @param reportDataList * @return {@link File} object */ @SuppressWarnings("unused") private File createGLClosureAccountBalanceReportExcelFile( final Collection<GLClosureAccountBalanceReportData> reportDataList) { File file = null; try { if (reportDataList != null) { final String[] columnTitles = new String[13]; columnTitles[0] = "AccountCostCentre"; columnTitles[1] = "AccountDepartment"; columnTitles[2] = "AccountNumber"; columnTitles[3] = "TransactionType"; columnTitles[4] = "TransactionDate"; columnTitles[5] = "GoodsAmount"; columnTitles[6] = "Reference"; columnTitles[7] = "Narrative"; columnTitles[8] = "UniqueReferenceNumber"; columnTitles[9] = "UserNumber"; columnTitles[10] = "Source"; columnTitles[11] = "PostedDate"; columnTitles[12] = "TransactionAnalysisCode"; XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet spreadsheet = workbook.createSheet(" nominaltransactions "); XSSFRow row; XSSFFont font; XSSFCellStyle style; XSSFDataFormat dataFormat; int rowId = 0; int cellId = 0; row = spreadsheet.createRow(rowId++); for (String columnTitle : columnTitles) { font = workbook.createFont(); style = workbook.createCellStyle(); font.setBold(true); font.setFontName("Arial"); font.setFontHeightInPoints((short) 10); style.setFont(font); Cell cell = row.createCell(cellId++); cell.setCellValue(columnTitle); cell.setCellStyle(style); } for (GLClosureAccountBalanceReportData reportData : reportDataList) { row = spreadsheet.createRow(rowId++); font = workbook.createFont(); dataFormat = workbook.createDataFormat(); font.setFontName("Arial"); font.setFontHeightInPoints((short) 10); font.setBold(false); // ==================================================== Cell cell = row.createCell(2); style = workbook.createCellStyle(); cell.setCellType(Cell.CELL_TYPE_STRING); style.setDataFormat(dataFormat.getFormat("@")); style.setFont(font); cell.setCellValue(reportData.getAccountNumber()); cell.setCellStyle(style); // ==================================================== // ==================================================== if (reportData.getTransactionType() != null) { cell = row.createCell(3); style = workbook.createCellStyle(); style.setFont(font); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(reportData.getTransactionType().getValue()); cell.setCellStyle(style); } // ==================================================== // ==================================================== if (reportData.getTransactionDate() != null) { cell = row.createCell(4); style = workbook.createCellStyle(); Date transactionDate = reportData.getTransactionDate().toDate(); style.setDataFormat(dataFormat.getFormat("MM/DD/YY")); style.setFont(font); cell.setCellValue(transactionDate); cell.setCellStyle(style); } // ==================================================== // ==================================================== if (reportData.getAmount() != null) { cell = row.createCell(5); style = workbook.createCellStyle(); Double amount = reportData.getAmount().doubleValue(); style.setDataFormat(dataFormat.getFormat("0.00")); style.setFont(font); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(amount); cell.setCellStyle(style); } // ==================================================== // ==================================================== if (reportData.getReference() != null) { cell = row.createCell(6); style = workbook.createCellStyle(); cell.setCellType(Cell.CELL_TYPE_STRING); style.setDataFormat(dataFormat.getFormat("@")); style.setFont(font); cell.setCellValue(reportData.getReference()); cell.setCellStyle(style); } // ==================================================== // ==================================================== if (reportData.getPostedDate() != null) { cell = row.createCell(11); style = workbook.createCellStyle(); Date postedDate = reportData.getPostedDate().toDate(); style.setDataFormat(dataFormat.getFormat("MM/DD/YY")); style.setFont(font); cell.setCellValue(postedDate); cell.setCellStyle(style); } // ==================================================== } final String fileDirectory = FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator + ""; if (!new File(fileDirectory).isDirectory()) { new File(fileDirectory).mkdirs(); } file = new File(fileDirectory + "gl_closure_account_balance_report.xls"); FileOutputStream fileOutputStream = new FileOutputStream(file); workbook.write(fileOutputStream); fileOutputStream.close(); } } catch (Exception exception) { logger.error(exception.getMessage(), exception); } return file; }
From source file:org.apache.ofbiz.pricat.AbstractPricatParser.java
License:Apache License
public void writeCommentsToFile(XSSFWorkbook workbook, XSSFSheet sheet) { report.println();//from w w w. j a v a 2 s.co m report.print(UtilProperties.getMessage(resource, "WriteCommentsBackToExcel", locale), InterfaceReport.FORMAT_NOTE); FileOutputStream fos = null; XSSFCreationHelper factory = workbook.getCreationHelper(); XSSFFont boldFont = workbook.createFont(); boldFont.setFontName("Arial"); boldFont.setBold(true); boldFont.setCharSet(134); boldFont.setFontHeightInPoints((short) 9); XSSFFont plainFont = workbook.createFont(); plainFont.setFontName("Arial"); plainFont.setCharSet(134); plainFont.setFontHeightInPoints((short) 9); XSSFSheet errorSheet = null; if (errorMessages.keySet().size() > 0) { String errorSheetName = UtilDateTime.nowDateString("yyyy-MM-dd HHmm") + " Errors"; errorSheetName = WorkbookUtil.createSafeSheetName(errorSheetName); errorSheet = workbook.createSheet(errorSheetName); workbook.setSheetOrder(errorSheetName, 0); workbook.setActiveSheet(workbook.getSheetIndex(errorSheetName)); XSSFDrawing drawingPatriarch = errorSheet.getDrawingPatriarch(); if (drawingPatriarch == null) { drawingPatriarch = errorSheet.createDrawingPatriarch(); } for (int i = 0; i <= getHeaderRowNo(); i++) { XSSFRow newRow = errorSheet.createRow(i); XSSFRow row = sheet.getRow(i); newRow.setHeight(row.getHeight()); copyRow(row, newRow, factory, drawingPatriarch); } // copy merged regions for (int i = 0; i < sheet.getNumMergedRegions(); i++) { CellRangeAddress mergedRegion = sheet.getMergedRegion(i); if (mergedRegion.getFirstRow() < getHeaderRowNo()) { errorSheet.addMergedRegion(mergedRegion); } } // copy images List<XSSFPictureData> pics = workbook.getAllPictures(); List<XSSFShape> shapes = sheet.getDrawingPatriarch().getShapes(); for (int i = 0; i < shapes.size(); i++) { XSSFShape shape = shapes.get(i); XSSFAnchor anchor = shape.getAnchor(); if (shape instanceof XSSFPicture && anchor instanceof XSSFClientAnchor) { XSSFPicture pic = (XSSFPicture) shape; XSSFClientAnchor clientAnchor = (XSSFClientAnchor) anchor; if (clientAnchor.getRow1() < getHeaderRowNo()) { for (int j = 0; j < pics.size(); j++) { XSSFPictureData picture = pics.get(j); if (picture.getPackagePart().getPartName() .equals(pic.getPictureData().getPackagePart().getPartName())) { drawingPatriarch.createPicture(clientAnchor, j); } } } } } } try { // set comments in the original sheet XSSFDrawing patriarch = sheet.getDrawingPatriarch(); for (CellReference cell : errorMessages.keySet()) { if (cell != null && errorMessages.get(cell) != null) { XSSFComment comment = sheet.getCellComment(new CellAddress(cell.getRow(), cell.getCol())); boolean isNewComment = false; if (comment == null) { XSSFClientAnchor anchor = factory.createClientAnchor(); anchor.setDx1(100); anchor.setDx2(100); anchor.setDy1(100); anchor.setDy2(100); anchor.setCol1(cell.getCol()); anchor.setCol2(cell.getCol() + 4); anchor.setRow1(cell.getRow()); anchor.setRow2(cell.getRow() + 4); anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); comment = patriarch.createCellComment(anchor); isNewComment = true; } XSSFRichTextString rts = factory.createRichTextString("OFBiz PriCat:\n"); rts.applyFont(boldFont); rts.append(errorMessages.get(cell), plainFont); comment.setString(rts); comment.setAuthor("Apache OFBiz PriCat"); if (isNewComment) { sheet.getRow(cell.getRow()).getCell(cell.getCol()).setCellComment(comment); OFBizPricatUtil.formatCommentShape(sheet, cell); } } } // set comments in the new error sheet XSSFDrawing errorPatriarch = errorSheet.getDrawingPatriarch(); int newRowNum = getHeaderRowNo() + 1; Map<Integer, Integer> rowMapping = new HashMap<Integer, Integer>(); for (CellReference cell : errorMessages.keySet()) { if (cell != null && errorMessages.get(cell) != null) { XSSFRow row = sheet.getRow(cell.getRow()); Integer rowNum = Integer.valueOf(row.getRowNum()); int errorRow = newRowNum; if (rowMapping.containsKey(rowNum)) { errorRow = rowMapping.get(rowNum).intValue(); } else { XSSFRow newRow = errorSheet.getRow(errorRow); if (newRow == null) { newRow = errorSheet.createRow(errorRow); } rowMapping.put(rowNum, Integer.valueOf(errorRow)); newRow.setHeight(row.getHeight()); copyRow(row, newRow, factory, errorPatriarch); newRowNum++; } } } // write to file if (sequenceNum > 0L) { File commentedExcel = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx"); fos = new FileOutputStream(commentedExcel); workbook.write(fos); } else { fos = new FileOutputStream(pricatFile); workbook.write(fos); } fos.flush(); fos.close(); workbook.close(); } catch (FileNotFoundException e) { report.println(e); Debug.logError(e, module); } catch (IOException e) { report.println(e); Debug.logError(e, module); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { Debug.logError(e, module); } } if (workbook != null) { try { workbook.close(); } catch (IOException e) { Debug.logError(e, module); } } } report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK); report.println(); }
From source file:org.appdynamics.licensecount.file.WriteExcelDoc.java
public void init() { XSSFWorkbook workbook = new XSSFWorkbook(); //Create a blank sheet XSSFSheet licenseSummary = workbook.createSheet(LicenseS.LICENSE_SUMMARY); XSSFSheet licenseTiers = workbook.createSheet(LicenseS.TIER_SUMMARY); XSSFSheet licenseHourlyTiers = workbook.createSheet(LicenseS.HOURLY_TIER_SUMMARY); XSSFSheet licenseNodeInfo = workbook.createSheet(LicenseS.NODE_INFO_SUMMARY); XSSFSheet licenseNoNodeTiers = workbook.createSheet(LicenseS.TIERS_WITH_NO_NODES); style = workbook.createCellStyle();//from w ww . ja va2 s. c o m style.setAlignment(HorizontalAlignment.RIGHT); addNodeInfo(licenseNodeInfo); addTierWNoNodeInfo(licenseNoNodeTiers); // Lets create the first row which will be the header. int headerRowIndex = 0; Row headerRow = licenseSummary.createRow(headerRowIndex); Row tierRow = licenseTiers.createRow(headerRowIndex); Row hourlyTierRow = licenseHourlyTiers.createRow(headerRowIndex); int i = 0; Cell cell_1 = headerRow.createCell(i); cell_1.setCellValue(LicenseS.CUSTOMER_NAME); Cell cell_2 = tierRow.createCell(i); cell_2.setCellValue(LicenseS.APPLICATION_NAME); cell_2 = tierRow.createCell(i + 1); cell_2.setCellValue(LicenseS.TIER_NAME); Cell cell_3 = hourlyTierRow.createCell(i); cell_3.setCellValue(LicenseS.APPLICATION_NAME); cell_3 = hourlyTierRow.createCell(i + 1); cell_3.setCellValue(LicenseS.TIER_NAME); i += 2; int columnCount = 2; int columnCount1 = 3; // Create the date headers for (CustomerLicenseRange cRange : customer.getCustomerRangeValues()) { cell_1 = headerRow.createCell(columnCount); cell_1.setCellValue(cRange.getColumnName()); cell_2 = tierRow.createCell(columnCount1); cell_2.setCellValue(cRange.getColumnName()); columnCount++; columnCount1++; } i = addCustomer(licenseSummary, i); //logger.log(Level.INFO,"Next row " + ++i); headerRow = licenseSummary.createRow(++i); cell_1 = headerRow.createCell(0); cell_1.setCellValue(LicenseS.APPLICATION_NAME); i++; int tierRowCount = 2; int createdHourlyTierHeader = 0; columnCount1 = 3; //logger.log(Level.INFO,new StringBuilder().append("\n\n\tNumber of applications ").append(customer.getApplications().size()).toString()); for (ApplicationLicenseCount app : customer.getApplications().values()) { i = addApplication(licenseSummary, i, app); int inCount = 0; for (TierLicenseCount tier : app.getTierLicenses().values()) { if (createdHourlyTierHeader == 0) { for (TierHourLicenseRange tr : tier.getTierHourLicenseRange()) { cell_3 = hourlyTierRow.createCell(columnCount1); cell_3.setCellValue(tr.getHourColumnName()); columnCount1++; } createdHourlyTierHeader = 1; } tierRowCount = addTier(licenseTiers, tierRowCount, tier, app.getApplicationName(), inCount); inCount++; } if (inCount != 0) tierRowCount++; i++; } tierRowCount = 2; for (ApplicationLicenseCount app : customer.getApplications().values()) { //i=addApplication(licenseSummary,i,app); int inCount = 0; tierRowCount = addHourlyApp(licenseHourlyTiers, tierRowCount, app, inCount); for (TierLicenseCount tier : app.getTierLicenses().values()) { tierRowCount = addHourlyTier(licenseHourlyTiers, tierRowCount, tier, app.getApplicationName(), inCount); inCount++; } tierRowCount++; i++; } try { //Write the workbook in file system //String fileName=new StringBuilder().append("/Users/gilbert.solorzano/Documents/").append(customer.getName()).append("LicenseFile.xlsx").toString(); FileOutputStream out = new FileOutputStream(new File(LicenseS.FILENAME_V)); workbook.write(out); out.close(); StringBuilder bud = new StringBuilder(); bud.append("Completed writing the file: ").append(LicenseS.FILENAME_V).append("."); logger.log(Level.INFO, bud.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.appdynamics.utilreports.files.ProcessExcelFile.java
public void init() { XSSFWorkbook workbook = new XSSFWorkbook(); //logger.log(Level.INFO,"Start excel sheet."); for (GatherLoadCheck glc : loadChecks) { //String app=glc.getLc().getApplication(); //Create a blank sheet for (LoadCheck lc : glc.getLoadCheckList()) { //logger.log(Level.INFO,new StringBuilder().append("Sheet Name ").append(lc.getSheetName()).append(", ").append(lc.getAppName()).toString()); XSSFSheet _sheet = workbook.createSheet(new StringBuilder().append(lc.getSheetName()) .append(AppDUtilReportS._U).append(lc.getAppId()).toString()); processCheck(_sheet, lc);/*from w w w . j a v a 2 s. co m*/ } } try { //Write the workbook in file system //String fileName=new StringBuilder().append("/Users/gilbert.solorzano/Documents/").append(customer.getName()).append("LicenseFile.xlsx").toString(); FileOutputStream out = new FileOutputStream(fileName); workbook.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.azkfw.doclet.jaxrs.writer.JAXRSXlsxDocletWriter.java
License:Apache License
public void write(final RootDoc root) { try {//from www . ja v a2 s. co m parser.addListener(new JAXRSDocletParserListener() { @Override public void jaxrsDocletParserFindMethodDoc(JAXRSDocletParserEvent event, ClassDoc classDoc, MethodDoc methodDoc) { } @Override public void jaxrsDocletParserFindClassDoc(JAXRSDocletParserEvent event, ClassDoc classDoc) { } @Override public void jaxrsDocletParserFindAreas(JAXRSDocletParserEvent event, AreasModel model) { } @Override public void jaxrsDocletParserFindAPI(final JAXRSDocletParserEvent event, final APIModel model) { addApi(model); } }); parser.parse(root); List<APIModel> bufApis = new ArrayList<>(); for (String key : apis.keySet()) { bufApis.add(apis.get(key)); } Collections.sort(bufApis, new Comparator<APIModel>() { @Override public int compare(APIModel o1, APIModel o2) { String s1 = o1.getPath(); String s2 = o2.getPath(); if (null == s1 && null == s2) { return 0; } else if (null == s2) { return 1; } else if (null == s1) { return -1; } else { return s1.compareTo(s2); } } }); XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheetAPIList = wb.createSheet("IF"); printSheet(wb, sheetAPIList, bufApis); for (APIModel api : bufApis) { if (null != api.getId() && 0 < api.getId().length()) { XSSFSheet sheetApi = wb.createSheet(api.getId()); printSheet(wb, sheetApi, api); } } FileOutputStream out = new FileOutputStream(new File("sample.xlsx")); wb.write(out); out.close(); } catch (DocletParserException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:org.azkfw.document.tools.DirectoryTreeDocument.java
License:Apache License
public boolean create(final File directory, final File destFile) { boolean result = false; countFile = 0;//from ww w.j a v a 2 s .c om maxCol = 0; try { imgFile = new Image(); imgDirectory = new Image(); imgFile.load(this.getClass().getResourceAsStream("/file.png")); imgDirectory.load(this.getClass().getResourceAsStream("/directory.png")); XSSFWorkbook wb = new XSSFWorkbook(); sheet = wb.createSheet("?"); DirectoryParser parser = new BasicDirectoryParser(); parser.setDecorator(decorator); parser.addListener(new DirectoryParserListener() { @Override public void documentParserCallback(final DirectoryParserEvent event) { onFindFile(event); } }); parser.parse(directory); // for (int col = 0; col <= maxCol; col++) { sheet.setColumnWidth(offsetCol + col, 2 * 256 + 60); } FileOutputStream out = new FileOutputStream(destFile); wb.write(out); out.close(); // image imgFile.release(); imgDirectory.release(); result = true; } catch (Exception ex) { ex.printStackTrace(); } finally { } return result; }
From source file:org.codelabor.example.poi.xssf.usermodel.XSSFWorkbookTest.java
License:Apache License
@Test public void testCreateSheet() { String path = "C:/temp/workbook2.xlsx"; OutputStream outputStream = null; try {/*ww w . j a v a 2 s . c o m*/ XSSFWorkbook workbook = new XSSFWorkbook(); workbook.createSheet("Sheet1"); workbook.createSheet("Sheet2"); outputStream = new FileOutputStream(path); workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); fail(); } finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }