List of usage examples for org.apache.poi.ss.usermodel Workbook createSheet
Sheet createSheet(String sheetname);
From source file:com.dufeng.core.BusinessPlan.java
License:Apache License
public static void main(String[] args) throws Exception { Workbook wb; if (args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); else/*from w w w . j av a 2 s . com*/ wb = new XSSFWorkbook(); Map<String, CellStyle> styles = createStyles(wb); Sheet sheet = wb.createSheet("Business Plan"); //turn off gridlines sheet.setDisplayGridlines(false); sheet.setPrintGridlines(false); sheet.setFitToPage(true); sheet.setHorizontallyCenter(true); PrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(true); //the following three statements are required only for HSSF sheet.setAutobreaks(true); printSetup.setFitHeight((short) 1); printSetup.setFitWidth((short) 1); //the header row: centered text in 48pt font Row headerRow = sheet.createRow(0); headerRow.setHeightInPoints(12.75f); for (int i = 0; i < titles.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(titles[i]); cell.setCellStyle(styles.get("header")); } //columns for 11 weeks starting from 9-Jul Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); //calendar.setTime(fmt.parse("9-Jul")); calendar.setTime(new Date()); calendar.set(Calendar.YEAR, year); for (int i = 0; i < 11; i++) { Cell cell = headerRow.createCell(titles.length + i); cell.setCellValue(calendar); cell.setCellStyle(styles.get("header_date")); calendar.roll(Calendar.WEEK_OF_YEAR, true); } //freeze the first row sheet.createFreezePane(0, 1); Row row; Cell cell; int rownum = 1; for (int i = 0; i < data.length; i++, rownum++) { row = sheet.createRow(rownum); if (data[i] == null) continue; for (int j = 0; j < data[i].length; j++) { cell = row.createCell(j); String styleName; boolean isHeader = i == 0 || data[i - 1] == null; switch (j) { case 0: if (isHeader) { styleName = "cell_b"; cell.setCellValue(Double.parseDouble(data[i][j])); } else { styleName = "cell_normal"; cell.setCellValue(data[i][j]); } break; case 1: if (isHeader) { styleName = i == 0 ? "cell_h" : "cell_bb"; } else { styleName = "cell_indented"; } cell.setCellValue(data[i][j]); break; case 2: styleName = isHeader ? "cell_b" : "cell_normal"; cell.setCellValue(data[i][j]); break; case 3: styleName = isHeader ? "cell_b_centered" : "cell_normal_centered"; cell.setCellValue(Integer.parseInt(data[i][j])); break; case 4: { //calendar.setTime(fmt.parse(data[i][j])); calendar.setTime(new Date()); calendar.set(Calendar.YEAR, year); cell.setCellValue(calendar); styleName = isHeader ? "cell_b_date" : "cell_normal_date"; break; } case 5: { int r = rownum + 1; String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")"; cell.setCellFormula(fmla); styleName = isHeader ? "cell_bg" : "cell_g"; break; } default: styleName = data[i][j] != null ? "cell_blue" : "cell_normal"; } cell.setCellStyle(styles.get(styleName)); } } //group rows for each phase, row numbers are 0-based sheet.groupRow(4, 6); sheet.groupRow(9, 13); sheet.groupRow(16, 18); //set column widths, the width is measured in units of 1/256th of a character width sheet.setColumnWidth(0, 256 * 6); sheet.setColumnWidth(1, 256 * 33); sheet.setColumnWidth(2, 256 * 20); sheet.setZoom(3, 4); // Write the output to a file String file = "E:/businessplan.xls"; if (wb instanceof XSSFWorkbook) file += "x"; FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); }
From source file:com.emi.loan.test.ExportToExcel.java
public static void main(String[] args) { try {// w w w . j a v a 2s .com //Populate DefaultTableModel data DefaultTableModel dtm = new DefaultTableModel(); Vector<String> cols = new Vector<String>(); dtm.addColumn("Col 1"); dtm.addColumn("Col 2"); dtm.addColumn("Col 3"); Vector<String> dtmrow = null; for (int i = 1; i <= 10; i++) { dtmrow = new Vector<String>(); for (int j = 1; j <= 3; j++) { dtmrow.add("Cell " + j + "." + i); } dtm.addRow(dtmrow); } //Exporting to Excel Workbook wb = new HSSFWorkbook(); CreationHelper createhelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("new sheet"); Row row = null; Cell cell = null; for (int i = 0; i < dtm.getRowCount(); i++) { row = sheet.createRow(i); for (int j = 0; j < dtm.getColumnCount(); j++) { cell = row.createCell(j); cell.setCellValue((String) dtm.getValueAt(i, j)); } } FileOutputStream out = new FileOutputStream(new File("C:\\26276\\workbook.xls")); wb.write(out); out.close(); } catch (FileNotFoundException ex) { Logger.getLogger(ExportToExcel.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ExportToExcel.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.emi.loan.util.Utilities.java
public static void exportTOExcel(DefaultTableModel dtm, Map<String, String> ln_info) { FileOutputStream out = null;//from w w w .j a v a 2 s . c o m try { Workbook wb = new HSSFWorkbook(); // CreationHelper createhelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("EMI TABLE"); Row row; Cell cell; File file = chooseFile(); out = new FileOutputStream(file); HSSFFont headerFont = (HSSFFont) wb.createFont(); headerFont.setFontHeightInPoints((short) 12); headerFont.setFontName("CENTURY GOTHIC"); headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); headerFont.setColor(HSSFColor.WHITE.index); HSSFFont infoFont = (HSSFFont) wb.createFont(); infoFont.setFontHeightInPoints((short) 14); infoFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // HSSFFont font = (HSSFFont) wb.createFont(); // font.setFontHeightInPoints((short) 10); // font.setFontName("CENTURY GOTHIC"); // font.setColor(HSSFColor.BLACK.index); CellStyle defaultStyle = wb.createCellStyle(); defaultStyle.setFillForegroundColor(HSSFColor.AQUA.index); defaultStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); defaultStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY); defaultStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_JUSTIFY); defaultStyle.setFont(headerFont); CellStyle borderStyle = wb.createCellStyle(); borderStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM); borderStyle.setFont(infoFont); row = sheet.createRow(1); cell = row.createCell(0); cell.setCellStyle(defaultStyle); cell.setCellValue("Loan Amount(Rs.)"); cell = row.createCell(1); cell.setCellStyle(borderStyle); cell.setCellValue(Double.parseDouble(ln_info.get("Loan Amount"))); row = sheet.createRow(3); cell = row.createCell(0); cell.setCellStyle(defaultStyle); cell.setCellValue("Interest %"); cell = row.createCell(1); cell.setCellStyle(borderStyle); cell.setCellValue(Double.parseDouble(ln_info.get("Interest"))); row = sheet.createRow(5); cell = row.createCell(0); cell.setCellStyle(defaultStyle); cell.setCellValue("Period (months)"); cell = row.createCell(1); cell.setCellStyle(borderStyle); cell.setCellValue(Integer.parseInt(ln_info.get("Period"))); for (int i = 0; i <= dtm.getRowCount(); i++) { row = sheet.createRow(i + 8); for (int j = 0; j < dtm.getColumnCount(); j++) { cell = row.createCell(j); if (i == 0) { // writing the column headers cell.setCellStyle(defaultStyle); cell.setCellValue(dtm.getColumnName(j)); } else if (j == 0 || j == 5) { cell.setCellValue(Integer.parseInt(dtm.getValueAt(i - 1, j).toString())); } else { cell.setCellValue(Double.parseDouble(dtm.getValueAt(i - 1, j).toString())); } } } row = sheet.createRow(dtm.getRowCount() + 12); cell = row.createCell(0); cell.setCellValue("-- END OF REPORT --"); for (int j = 0; j < dtm.getColumnCount(); j++) { sheet.autoSizeColumn(j, true); } wb.write(out); } catch (FileNotFoundException ex) { System.out.println("File not Found"); Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { System.out.println("IOException"); Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex); } finally { try { out.close(); } catch (IOException ex) { Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.esri.geoevent.test.performance.report.XLSXReportWriter.java
License:Apache License
@Override public void writeReport(String reportFile, List<String> testNames, List<String> columnNames, Map<String, List<FixtureStatistic>> stats) throws IOException { //create the parent directories - if needed createParentDirectoriesIfNeeded(reportFile); // rollover the file - keep backups rollOver(reportFile);//w w w. jav a 2 s. c om Workbook workbook = null; try { workbook = new XSSFWorkbook(); // header style CellStyle headerStyle = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); headerStyle.setFont(font); // copy the column names - add the test name as the first column List<String> columnNamesCopy = new ArrayList<String>(); columnNamesCopy.add("Test Name"); columnNamesCopy.addAll(columnNames); // create the sheet Sheet sheet = workbook.createSheet("Summary"); // create the header row int rowIndex = 0; Row headers = sheet.createRow(rowIndex); headers.setRowStyle(headerStyle); int cellIndex = 0; for (String columnName : columnNamesCopy) { Cell cell = headers.createCell(cellIndex); cell.setCellValue(columnName); cell.setCellStyle(headerStyle); cellIndex++; } for (String testName : testNames) { // get each test's fixture stats and sort them accordingly List<FixtureStatistic> fixtureStats = stats.get(testName); if (fixtureStats == null || fixtureStats.size() == 0) { continue; } Collections.sort(fixtureStats); rowIndex++; for (FixtureStatistic fixtureStat : fixtureStats) { Row data = sheet.createRow(rowIndex); cellIndex = 0; //write out the test name first Cell cell = data.createCell(cellIndex); cell.setCellValue(testName); cellIndex++; for (String columnName : columnNames) { cell = data.createCell(cellIndex); Object rawValue = fixtureStat.getStat(columnName); if (rawValue == null) { cell.setCellValue(""); } else { if (rawValue instanceof Integer) { cell.setCellValue((Integer) rawValue); } else if (rawValue instanceof Double) { cell.setCellValue((Double) rawValue); } else if (rawValue instanceof Long) { cell.setCellValue((Long) rawValue); } else if (rawValue instanceof Boolean) { cell.setCellValue((Boolean) rawValue); } else { cell.setCellValue(rawValue.toString()); } } // adjust column width to fit the content sheet.autoSizeColumn(cellIndex); cellIndex++; } //rowIndex++; } } //write out the total time if (getTotalTestingTime() != -1) { rowIndex = rowIndex + 2; Row data = sheet.createRow(rowIndex); Cell cell = data.createCell(0); cell.setCellValue("Total Testing Time:"); cell.setCellStyle(headerStyle); cell = data.createCell(1); cell.setCellValue(formatTime(getTotalTestingTime())); } } finally { // write out the file FileOutputStream out = null; try { String fullPath = FilenameUtils.getFullPathNoEndSeparator(reportFile); // create all non exists folders else you will hit FileNotFoundException for report file path new File(fullPath).mkdirs(); out = new FileOutputStream(reportFile); if (workbook != null) { workbook.write(out); } } finally { IOUtils.closeQuietly(out); } } }
From source file:com.eurodyn.qlack2.fuse.lexicon.impl.LanguageServiceImpl.java
License:EUPL
@Override @Transactional(TxType.REQUIRED)//from w w w . j av a 2s . co m public byte[] downloadLanguage(String languageID) { byte[] retVal = null; // Check that the language exists and get its translations Language language = Language.find(languageID, em); // Create an Excel workbook. The workbook will contain a sheet for each // group. Workbook wb = new HSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); // Iterate over all existing groups and create a sheet for each one. // Creating a new list below and not using the one retrieved from // Group.getAllGroups since result lists are read only and // we need to add the empty group below to the list. List<Group> groups = new ArrayList<>(Group.getAllGroups(em)); // Add an dummy entry to the list to also check for translations without // a group. Group emptyGroup = new Group(); emptyGroup.setId(null); emptyGroup.setTitle("<No group>"); groups.add(0, emptyGroup); for (Group group : groups) { Map<String, String> translations; translations = keyService.getTranslationsForGroupAndLocale(group.getId(), language.getLocale()); if (!translations.isEmpty()) { Sheet sheet = wb.createSheet(group.getTitle()); // Add the header. Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue(createHelper.createRichTextString("Key")); headerRow.createCell(1).setCellValue(createHelper.createRichTextString("Translation")); // Add the data. int rowCounter = 1; for (String key : translations.keySet()) { Row row = sheet.createRow(rowCounter++); row.createCell(0).setCellValue(createHelper.createRichTextString(key)); row.createCell(1).setCellValue(createHelper.createRichTextString(translations.get(key))); } } } // Create the byte[] holding the Excel data. ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { wb.write(bos); retVal = bos.toByteArray(); } catch (IOException ex) { // Convert to a runtime exception in order to roll back transaction LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex); throw new QLanguageProcessingException("Error creating Excel file for language " + languageID); } return retVal; }
From source file:com.excelsiorsoft.transformer.TransformationHandler.java
License:Apache License
/** * Actual Spring Integration transformation handler. * * @param inputMessage Spring Integration input message * @return New Spring Integration message with updated headers *//* ww w .jav a 2 s . c om*/ @Transformer public Message<byte[]> handleFile(final Message<File> inputMessage) { final File inputFile = inputMessage.getPayload(); final String filename = inputFile.getName(); final String inputAsString; try { inputAsString = FileUtils.readFileToString(inputFile); } catch (IOException e) { throw new IllegalStateException(e); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("Sample Sheet"); // Create a row and put some cells in it. Rows are 0 based. Row row = sheet.createRow((short) 0); // Create a cell and put a value in it. Cell cell = row.createCell(0); cell.setCellValue(inputAsString); try { wb.write(bout); } catch (IOException e) { throw new IllegalStateException(e); } final Message<byte[]> message = MessageBuilder.withPayload(bout.toByteArray()) .setHeader(FileHeaders.FILENAME, filename + ".xls").setHeader(FileHeaders.ORIGINAL_FILE, inputFile) .setHeader("file_size", inputFile.length()).build(); return message; }
From source file:com.exilant.exility.core.XlxUtil.java
License:Open Source License
private Workbook addSheet(Workbook workbook, String[][] data, String sheetName) { Sheet sheet = workbook.createSheet(sheetName); int rowIdx = 0; for (String[] dataRow : data) { Row row = sheet.createRow(rowIdx); rowIdx++;//from w w w .j a va 2 s. c o m int cellIdx = 0; for (String val : dataRow) { row.createCell(cellIdx).setCellValue(val); cellIdx++; } } return workbook; }
From source file:com.exilant.exility.core.XlxUtil.java
License:Open Source License
private Workbook copyToWorkbook(DataCollection dc, Workbook workbook) { /**//from w w w . j a va 2 s .com * values first */ Sheet sheet = workbook.createSheet(CommonFieldNames.VALUES_TABLE_NAME); Row header = sheet.createRow(0); Row dataRow = sheet.createRow(1); int colIdx = 0; String[] fieldNames = dc.getFieldNames(); for (String fieldName : fieldNames) { header.createCell(colIdx).setCellValue(fieldName); this.setValue(dataRow.createCell(colIdx), dc.getValue(fieldName)); colIdx++; } /** * would like to blatantly ignore lists as NO ONE is using it. Will wait * for a bug report :-) */ String[] gridNames = dc.getGridNames(); if (gridNames != null && gridNames.length == 0) { for (String gridName : gridNames) { this.addSheet(workbook, dc.getGrid(gridName)); } } return workbook; }
From source file:com.exilant.exility.core.XlxUtil.java
License:Open Source License
private void addSheet(Workbook workbook, Grid grid) { Sheet sheet = workbook.createSheet(grid.getName()); /**/* w ww. j av a2s. com*/ * let us first create empty rows, so that we can go my columns later. * First row is header; */ int nbrRows = grid.getNumberOfRows() + 1; for (int rowIdx = 0; rowIdx < nbrRows; rowIdx++) { sheet.createRow(rowIdx); } int colIdx = 0; for (String columnName : grid.getColumnNames()) { this.addColumn(sheet, colIdx, grid.getColumn(columnName), columnName); colIdx++; } }
From source file:com.eyeq.pivot4j.export.poi.ExcelExporter.java
License:Common Public License
/** * @param workbook// ww w . j a v a 2 s . c om * @return */ protected Sheet createSheet(RenderContext context, Workbook workbook) { Sheet newSheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(getSheetName(context, sheetIndex))); sheetIndex++; return newSheet; }