List of usage examples for org.apache.poi.ss.usermodel Workbook createSheet
Sheet createSheet();
From source file:ddf.metrics.reporting.internal.rrd4j.RrdMetricsRetriever.java
License:Open Source License
private void createSummary(Workbook wb, List<String> metricNames, String metricsDir, long startTime, long endTime, SUMMARY_INTERVALS summaryInterval) throws IOException, MetricsGraphException { // convert seconds to milliseconds startTime = TimeUnit.SECONDS.toMillis(startTime); endTime = TimeUnit.SECONDS.toMillis(endTime); DateTime reportStart = new DateTime(startTime, DateTimeZone.UTC); DateTime reportEnd = new DateTime(endTime, DateTimeZone.UTC); Sheet sheet = wb.createSheet(); wb.setSheetName(0,/* w w w . j a va2 s.com*/ reportStart.toString(SUMMARY_TIMESTAMP) + " to " + reportEnd.toString(SUMMARY_TIMESTAMP)); Row headingRow = sheet.createRow(0); int columnMax = 1; for (String metricName : metricNames) { MutableDateTime chunkStart = new MutableDateTime(reportStart); MutableDateTime chunkEnd = new MutableDateTime(chunkStart); Row row = sheet.createRow(metricNames.indexOf(metricName) + 1); int columnCounter = 1; Boolean isSum = null; while (reportEnd.compareTo(chunkEnd) > 0 && columnCounter < EXCEL_MAX_COLUMNS) { increment(chunkEnd, summaryInterval); if (chunkEnd.isAfter(reportEnd)) { chunkEnd.setMillis(reportEnd); } // offset range by one millisecond so rrd will calculate granularity correctly chunkEnd.addMillis(-1); MetricData metricData = getMetricData(getRrdFilename(metricsDir, metricName), TimeUnit.MILLISECONDS.toSeconds(chunkStart.getMillis()), TimeUnit.MILLISECONDS.toSeconds(chunkEnd.getMillis())); isSum = metricData.hasTotalCount(); chunkEnd.addMillis(1); if (headingRow.getCell(columnCounter) == null) { Cell headingRowCell = headingRow.createCell(columnCounter); headingRowCell.getCellStyle().setWrapText(true); headingRowCell.setCellValue(getTimestamp(chunkStart, chunkEnd, columnCounter, summaryInterval)); } Cell sumOrAvg = row.createCell(columnCounter); if (isSum) { sumOrAvg.setCellValue((double) metricData.getTotalCount()); } else { sumOrAvg.setCellValue(cumulativeRunningAverage(metricData.getValues())); } chunkStart.setMillis(chunkEnd); columnCounter++; } columnMax = columnCounter; if (isSum != null) { row.createCell(0).setCellValue(convertCamelCase(metricName) + " (" + (isSum ? "sum" : "avg") + ")"); } } for (int i = 0; i < columnMax; i++) { sheet.autoSizeColumn(i); } }
From source file:de.fraunhofer.sciencedataamanager.datamanager.SearchDefinitonExecutionDataManager.java
/** * * @param searchDefinitonExecutionList/*from w w w .j a v a2 s. com*/ * @param outputStream * @throws Exception */ public void exportToExcel(LinkedList<SearchDefinitonExecution> searchDefinitonExecutionList, OutputStream outputStream) throws Exception { Workbook currentWorkBook = new HSSFWorkbook(); int currenSheetCount = 0; for (SearchDefinitonExecution searchDefinitonExecution : searchDefinitonExecutionList) { Sheet currentSheet = currentWorkBook.createSheet(); currentSheet.setFitToPage(true); currentSheet.setHorizontallyCenter(true); currentSheet.createFreezePane(0, 1); currentWorkBook.setSheetName(currenSheetCount, searchDefinitonExecution.getSystemInstance().getName()); Row headerRow = currentSheet.createRow(0); headerRow.setHeightInPoints(12.75f); headerRow.createCell(0).setCellValue("ID"); headerRow.createCell(1).setCellValue("Title"); headerRow.createCell(2).setCellValue("Identifier 1"); headerRow.createCell(3).setCellValue("Identifier 2"); headerRow.createCell(4).setCellValue("Identifier 3"); headerRow.createCell(5).setCellValue("Identifier 4"); headerRow.createCell(6).setCellValue("Url 1"); headerRow.createCell(7).setCellValue("Url 2"); headerRow.createCell(8).setCellValue("Text 1"); headerRow.createCell(9).setCellValue("Publication Name"); headerRow.createCell(10).setCellValue("Issue Name"); headerRow.createCell(11).setCellValue("Publish Date"); headerRow.createCell(12).setCellValue("Volume"); headerRow.createCell(13).setCellValue("Start Page"); headerRow.createCell(14).setCellValue("Issue Identifier"); CellStyle style = currentWorkBook.createCellStyle(); Font headerFont = currentWorkBook.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setAlignment(CellStyle.ALIGN_CENTER); style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(headerFont); headerRow.setRowStyle(style); Row currentRow = null; int rowNum = 1; for (ScientificPaperMetaInformation scientificPaperMetaInformation : searchDefinitonExecution .getScientificPaperMetaInformation()) { currentRow = currentSheet.createRow(rowNum); currentRow.createCell(0).setCellValue(scientificPaperMetaInformation.getID()); currentRow.createCell(1).setCellValue(scientificPaperMetaInformation.getTitle()); currentRow.createCell(2).setCellValue(scientificPaperMetaInformation.getIdentifier_1()); currentRow.createCell(3).setCellValue(scientificPaperMetaInformation.getIdentifier_2()); currentRow.createCell(4).setCellValue(scientificPaperMetaInformation.getIdentifier_3()); currentRow.createCell(5).setCellValue(scientificPaperMetaInformation.getIdentifier_4()); currentRow.createCell(6).setCellValue(scientificPaperMetaInformation.getUrl_1()); currentRow.createCell(7).setCellValue(scientificPaperMetaInformation.getUrl_2()); currentRow.createCell(8).setCellValue(scientificPaperMetaInformation.getText_1()); currentRow.createCell(9).setCellValue(scientificPaperMetaInformation.getSrcTitle()); currentRow.createCell(10).setCellValue(scientificPaperMetaInformation.getScrPublisherName()); currentRow.createCell(11).setCellValue(scientificPaperMetaInformation.getSrcPublicationDate()); currentRow.createCell(12).setCellValue(scientificPaperMetaInformation.getSrcVolume()); currentRow.createCell(13).setCellValue(scientificPaperMetaInformation.getSrcStartPage()); currentRow.createCell(14).setCellValue(scientificPaperMetaInformation.getScrIdentifier_1()); rowNum++; } currenSheetCount++; } currentWorkBook.write(outputStream); outputStream.close(); }
From source file:de.fraunhofer.sciencedataamanager.exampes.export.ExcelDataExport.java
/** * * @param dataToExport The objects gets all the values, which should * exported./*from ww w. j av a 2 s . c om*/ * @param outputStream * @throws Exception */ @Override public void export(Map<String, Map<String, List<Object>>> allConnectorsToExport, OutputStream outputStream) throws Exception { Workbook currentWorkBook = new HSSFWorkbook(); int currenSheetCount = 0; for (String currentKey : allConnectorsToExport.keySet()) { Map<String, List<Object>> dataToExport = allConnectorsToExport.get(currentKey); List<String> columns = new ArrayList<String>(dataToExport.keySet()); List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>(); int size = dataToExport.values().iterator().next().size(); for (int i = 0; i < size; i++) { Map<String, Object> row = new HashMap<String, Object>(); for (String column : columns) { row.put(column, dataToExport.get(column).get(i)); } rows.add(row); } //for (SearchDefinitonExecution searchDefinitonExecution : searchDefinitonExecutionList) { Sheet currentSheet = currentWorkBook.createSheet(); currentSheet.setFitToPage(true); currentSheet.setHorizontallyCenter(true); currentSheet.createFreezePane(0, 1); currentWorkBook.setSheetName(currenSheetCount, currentKey); Row headerRow = currentSheet.createRow(0); headerRow.setHeightInPoints(12.75f); int headerColumnIndex = 0; for (String currentColumn : columns) { headerRow.createCell(headerColumnIndex).setCellValue(currentColumn); headerColumnIndex++; } CellStyle style = currentWorkBook.createCellStyle(); Font headerFont = currentWorkBook.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setAlignment(CellStyle.ALIGN_CENTER); style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(headerFont); headerRow.setRowStyle(style); Row currentRow = null; int rowNum = 1; int currentColum = 0; for (Map<String, Object> currentRow2 : rows) { currentRow = currentSheet.createRow(rowNum); for (String column : columns) { if (currentRow2.get(column) != null) { currentRow.createCell(currentColum).setCellValue(currentRow2.get(column).toString()); } currentColum++; } currentColum = 0; rowNum++; } currenSheetCount++; } currentWorkBook.write(outputStream); outputStream.close(); }
From source file:de.iteratec.iteraplan.businesslogic.exchange.nettoExport.NettoExcelTransformer.java
License:Open Source License
/**{@inheritDoc}**/ @Override/*from w w w. j a va 2s. c o m*/ public void transform(List<?> sourceList, OutputStream out, TypeOfBuildingBlock typeOfBuildingBlock) { ColumnStructure[] columns = tableStructure.getColumns(); try { Workbook workbook = createWorkbook(); Sheet sheet = workbook.createSheet(); configSheetName(sheet, typeOfBuildingBlock); Map<IteraExcelStyle, CellStyle> createdStyles = ExcelStylesCreator.createStyles(workbook); CellStyle headerStyle = createdStyles.get(IteraExcelStyle.HEADER); CellStyle dataStyle = createdStyles.get(IteraExcelStyle.DATA); CellStyle dataDateStyle = createdStyles.get(IteraExcelStyle.DATA_DATE); // Create cell style for numbers CellStyle numCellStyle = workbook.createCellStyle(); numCellStyle.cloneStyleFrom(dataStyle); short numFormatIndex = workbook.createDataFormat().getFormat("0.00"); numCellStyle.setDataFormat(numFormatIndex); Row headerRow = sheet.createRow(0); int nextCol = 0; for (ColumnStructure columnStructure : columns) { Cell headerCell = headerRow.createCell(nextCol); headerCell.setCellValue(columnStructure.getColumnHeader()); headerCell.setCellStyle(headerStyle); nextCol++; } int nextRow = 1; for (Object obj : sourceList) { if (obj instanceof BuildingBlock) { BuildingBlock bb = (BuildingBlock) obj; // skip virutal root element if (bb instanceof AbstractHierarchicalEntity<?>) { AbstractHierarchicalEntity<?> hierarchicalEntity = (AbstractHierarchicalEntity<?>) bb; if (hierarchicalEntity.isTopLevelElement()) { continue; } } Row row = sheet.createRow(nextRow); nextCol = 0; for (ColumnStructure columnStructure : columns) { Cell cell = row.createCell(nextCol); Object resolvedValue = columnStructure.resolveValue(bb); if (resolvedValue instanceof Date) { cell.setCellStyle(dataDateStyle); cell.setCellValue((Date) resolvedValue); } else if (resolvedValue instanceof Number) { cell.setCellStyle(numCellStyle); double doubleValue = ((Number) resolvedValue).doubleValue(); cell.setCellValue(doubleValue); } else { cell.setCellStyle(dataStyle); cell.setCellValue(String.valueOf(resolvedValue)); } ++nextCol; } ++nextRow; } } // auto format nextCol = 0; for (int col = 0; col < columns.length; col++) { sheet.autoSizeColumn(col); int columnCharWidth = sheet.getColumnWidth(col) / 256; if (columnCharWidth > MAX_COLUM_CHAR_WIDTH) { sheet.setColumnWidth(col, MAX_COLUM_CHAR_WIDTH * 256); } } workbook.write(out); out.flush(); } catch (IOException e) { e.printStackTrace(); } }
From source file:eancode.SearchEanPanelNormal.java
public void importexcel(JTable table, String path) throws FileNotFoundException { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet(); Row row = sheet.createRow(0);/* w w w . j a va 2 s . c o m*/ TableModel model = table.getModel(); for (int i = 0; i < model.getColumnCount(); i++) { row.createCell(i).setCellValue(model.getColumnName(i)); } for (int i = 0; i < model.getRowCount(); i++) { row = sheet.createRow(i + 1); for (int j = 0; j < model.getColumnCount(); j++) { row.createCell(j).setCellValue(model.getValueAt(i, j).toString()); } } FileOutputStream fileOut = new FileOutputStream(path); try { wb.write(fileOut); fileOut.close(); } catch (IOException ex) { Logger.getLogger(SearchEanPanelNormal.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.ucsd.hep.roofitexplorer.ExcelWorkbookProducer.java
License:Apache License
/** make a spreadsheet from the table model. Note that this does NOT * take into account any sorting / filtering applied when displaying * the table.//www . ja v a2s . c o m * @param model * @param sheet_name * @return */ public static Workbook makeHSSFWorkbook(TableModel model, String sheet_name) { Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(); wb.setSheetName(0, sheet_name); Cell cell = null; int numCols = model.getColumnCount(); // set title row Row row = sheet.createRow(0); for (int col = 0; col < numCols; ++col) { cell = row.createCell(col); cell.setCellValue(model.getColumnName(col)); } // now fill in data content int first_data_row_num = 2; int num_rows = model.getRowCount(); for (int rowIndex = 0; rowIndex < num_rows; rowIndex++) { row = sheet.createRow(rowIndex + first_data_row_num); for (int col = 0; col < numCols; ++col) { cell = row.createCell(col); Object value = model.getValueAt(rowIndex, col); if (value == null) continue; if (value instanceof Double) cell.setCellValue((Double) value); else cell.setCellValue(value.toString()); } // loop over all columns of this row } // loop over all data rows return wb; }
From source file:edu.ucsd.hep.roofitexplorer.ExcelWorkbookProducer.java
License:Apache License
/** similar to the above but running on the table itself (i.e. should * take into account filtering and sorting) *///w w w .j ava 2 s .com public static Workbook makeHSSFWorkbook(JTable table, String sheetName) { Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(); wb.setSheetName(0, sheetName); Cell cell = null; int num_columns = table.getColumnCount(); // set title row Row row = sheet.createRow(0); for (int col = 0; col < num_columns; ++col) { cell = row.createCell(col); cell.setCellValue(table.getColumnName(col)); } // now fill in data content int first_data_row_num = 2; int numRows = table.getRowCount(); for (int rowIndex = 0; rowIndex < numRows; ++rowIndex) { row = sheet.createRow(rowIndex + first_data_row_num); for (int col = 0; col < num_columns; ++col) { cell = row.createCell(col); Object value = table.getValueAt(rowIndex, col); if (value == null) continue; if (value instanceof Double) cell.setCellValue((Double) value); else cell.setCellValue(value.toString()); } // loop over all columns of this row } // loop over all data rows return wb; }
From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java
License:Apache License
/** * [Flow #-2] ? : ? ? ? ? ?/*from w w w .java 2s.co m*/ */ @Test public void testModifyCellContents() throws Exception { try { String content = "Use \n with word wrap on to create a new line"; short rownum = 2; int cellnum = 2; LOGGER.debug("testModifyCellContents start...."); StringBuffer sb = new StringBuffer(); sb.append(fileLocation).append("/").append("testModifyCellContents.xls"); if (!EgovFileUtil.isExistsFile(sb.toString())) { Workbook wbT = new HSSFWorkbook(); wbT.createSheet(); // ? ? excelService.createWorkbook(wbT, sb.toString()); } // ? Workbook wb = excelService.loadWorkbook(sb.toString()); LOGGER.debug("testModifyCellContents after loadWorkbook...."); Sheet sheet = wb.getSheetAt(0); Font f2 = wb.createFont(); CellStyle cs = wb.createCellStyle(); cs = wb.createCellStyle(); cs.setFont(f2); //Word Wrap MUST be turned on cs.setWrapText(true); Row row = sheet.createRow(rownum); row.setHeight((short) 0x349); Cell cell = row.createCell(cellnum); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(new HSSFRichTextString(content)); cell.setCellStyle(cs); sheet.setColumnWidth(20, (int) ((50 * 8) / ((double) 1 / 20))); //excelService.writeWorkbook(wb); FileOutputStream out = new FileOutputStream(sb.toString()); wb.write(out); out.close(); // ? Workbook wb1 = excelService.loadWorkbook(sb.toString()); Sheet sheet1 = wb1.getSheetAt(0); Row row1 = sheet1.getRow(rownum); Cell cell1 = row1.getCell(cellnum); // ? ? ? LOGGER.debug("cell ###{}###", cell1.getRichStringCellValue()); LOGGER.debug("cont ###{}###", content); assertNotSame("TEST", cell1.getRichStringCellValue().toString()); assertEquals(content, cell1.getRichStringCellValue().toString()); } catch (Exception e) { LOGGER.error(e.toString()); throw new Exception(e); } finally { LOGGER.debug("testModifyCellContents end...."); } }
From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java
License:Apache License
/** * [Flow #-4] ? : ? ? ?(Header, Footer)? *//*from w w w.j ava 2s . c o m*/ @Test public void testModifyDocAttribute() throws Exception { try { LOGGER.debug("testModifyDocAttribute start...."); StringBuffer sb = new StringBuffer(); sb.append(fileLocation).append("/").append("testModifyDocAttribute.xls"); if (EgovFileUtil.isExistsFile(sb.toString())) { EgovFileUtil.delete(new File(sb.toString())); LOGGER.debug("Delete file....{}", sb.toString()); } Workbook wbTmp = new HSSFWorkbook(); wbTmp.createSheet(); // ? ? excelService.createWorkbook(wbTmp, sb.toString()); // ? Workbook wb = excelService.loadWorkbook(sb.toString()); LOGGER.debug("testModifyCellContents after loadWorkbook...."); Sheet sheet = wb.createSheet("doc test sheet"); Row row = sheet.createRow(1); Cell cell = row.createCell(1); cell.setCellValue(new HSSFRichTextString("Header/Footer Test")); // Header Header header = sheet.getHeader(); header.setCenter("Center Header"); header.setLeft("Left Header"); header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") + HSSFHeader.fontSize((short) 16) + "Right Stencil-Normal Italic font and size 16"); // Footer Footer footer = sheet.getFooter(); footer.setCenter(HSSFHeader.font("Fixedsys", "Normal") + HSSFHeader.fontSize((short) 12) + "- 1 -"); LOGGER.debug("Style is ...{}", HSSFHeader.font("Fixedsys", "Normal"), HSSFHeader.fontSize((short) 12) + "- 1 -"); footer.setLeft("Left Footer"); footer.setRight("Right Footer"); // ? FileOutputStream out = new FileOutputStream(sb.toString()); wb.write(out); out.close(); assertTrue(EgovFileUtil.isExistsFile(sb.toString())); ////////////////////////////////////////////////////////////////////////// // ? Workbook wbT = excelService.loadWorkbook(sb.toString()); Sheet sheetT = wbT.getSheet("doc test sheet"); Header headerT = sheetT.getHeader(); assertEquals("Center Header", headerT.getCenter()); assertEquals("Left Header", headerT.getLeft()); assertEquals(HSSFHeader.font("Stencil-Normal", "Italic") + HSSFHeader.fontSize((short) 16) + "Right Stencil-Normal Italic font and size 16", headerT.getRight()); Footer footerT = sheetT.getFooter(); assertEquals("Right Footer", footerT.getRight()); assertEquals("Left Footer", footerT.getLeft()); assertEquals(HSSFHeader.font("Fixedsys", "Normal") + HSSFHeader.fontSize((short) 12) + "- 1 -", footerT.getCenter()); } catch (Exception e) { LOGGER.error(e.toString()); throw new Exception(e); } finally { LOGGER.debug("testModifyDocAttribute end...."); } }
From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java
License:Apache License
/** * [Flow #-5] : ?? ? ? ? //from www . j av a 2 s . c om */ @Test public void testGetCellContents() throws Exception { try { LOGGER.debug("testGetCellContents start...."); StringBuffer sb = new StringBuffer(); sb.append(fileLocation).append("/").append("testGetCellContents.xls"); if (EgovFileUtil.isExistsFile(sb.toString())) { EgovFileUtil.delete(new File(sb.toString())); LOGGER.debug("Delete file....{}", sb.toString()); } Workbook wbTmp = new HSSFWorkbook(); wbTmp.createSheet(); // ? ? excelService.createWorkbook(wbTmp, sb.toString()); // ? Workbook wb = excelService.loadWorkbook(sb.toString()); LOGGER.debug("testGetCellContents after loadWorkbook...."); Sheet sheet = wb.createSheet("cell test sheet"); CellStyle cs = wb.createCellStyle(); cs = wb.createCellStyle(); cs.setWrapText(true); for (int i = 0; i < 100; i++) { Row row = sheet.createRow(i); for (int j = 0; j < 5; j++) { Cell cell = row.createCell(j); cell.setCellValue(new HSSFRichTextString("row " + i + ", cell " + j)); cell.setCellStyle(cs); } } // ? FileOutputStream out = new FileOutputStream(sb.toString()); wb.write(out); out.close(); ////////////////////////////////////////////////////////////////////////// // ? Workbook wbT = excelService.loadWorkbook(sb.toString()); Sheet sheetT = wbT.getSheet("cell test sheet"); for (int i = 0; i < 100; i++) { Row row1 = sheetT.getRow(i); for (int j = 0; j < 5; j++) { Cell cell1 = row1.getCell(j); LOGGER.debug("row {}, cell {} : {}", i, j, cell1.getRichStringCellValue()); assertEquals("row " + i + ", cell " + j, cell1.getRichStringCellValue().toString()); } } } catch (Exception e) { LOGGER.error(e.toString()); throw new Exception(e); } finally { LOGGER.debug("testGetCellContents end...."); } }