List of usage examples for org.apache.poi.ss.usermodel Sheet createFreezePane
void createFreezePane(int colSplit, int rowSplit);
From source file:org.zephyrsoft.sdb2.StatisticsController.java
License:Open Source License
public void exportStatisticsAll(SongsModel songs, File targetExcelFile) { // collect basic data Map<String, Song> songsByUUID = new HashMap<>(); for (Song song : songs) { songsByUUID.put(song.getUUID(), song); }/* ww w . j a v a 2s . c om*/ List<String> months = statistics.getUsedMonths(); // create a new workbook Workbook workbook = new HSSFWorkbook(); // define formats CellStyle integerStyle = workbook.createCellStyle(); DataFormat df = workbook.createDataFormat(); integerStyle.setDataFormat(df.getFormat("0")); CellStyle textStyle = workbook.createCellStyle(); textStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text")); CellStyle textBoldStyle = workbook.createCellStyle(); textBoldStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text")); org.apache.poi.ss.usermodel.Font font = workbook.createFont(); font.setColor(org.apache.poi.ss.usermodel.Font.COLOR_RED); font.setBoldweight(org.apache.poi.ss.usermodel.Font.BOLDWEIGHT_BOLD); textBoldStyle.setFont(font); for (String month : months) { Map<String, Integer> monthStatsByUUID = statistics.getStatisticsForMonth(month); Map<Song, Integer> monthStatsBySong = new TreeMap<>(); for (String uuid : monthStatsByUUID.keySet()) { Song song = songs.getByUUID(uuid); if (song != null) { monthStatsBySong.put(song, monthStatsByUUID.get(uuid)); } else { LOG.info("no song found in database for UUID {}", uuid); } } Sheet sheet = workbook.createSheet(month); Row row = null; int rownum = 0; row = sheet.createRow(rownum); int cellnum = 0; addTextCell(row, cellnum++, textBoldStyle, "Presentation Count"); addTextCell(row, cellnum++, textBoldStyle, "Song Title"); addTextCell(row, cellnum++, textBoldStyle, "Composer (Music)"); addTextCell(row, cellnum++, textBoldStyle, "Author (Text)"); addTextCell(row, cellnum++, textBoldStyle, "Publisher"); addTextCell(row, cellnum++, textBoldStyle, "Copyright Notes"); addTextCell(row, cellnum++, textBoldStyle, "Song Lyrics"); rownum++; for (Song song : monthStatsBySong.keySet()) { row = sheet.createRow(rownum); cellnum = 0; addIntegerCell(row, cellnum++, integerStyle, monthStatsBySong.get(song)); addTextCell(row, cellnum++, textStyle, song.getTitle()); addTextCell(row, cellnum++, textStyle, song.getComposer()); addTextCell(row, cellnum++, textStyle, song.getAuthorText()); addTextCell(row, cellnum++, textStyle, song.getPublisher()); addTextCell(row, cellnum++, textStyle, song.getAdditionalCopyrightNotes()); addTextCell(row, cellnum++, textStyle, song.getLyrics()); rownum++; } for (int i = 0; i < cellnum; i++) { sheet.autoSizeColumn(i); } sheet.createFreezePane(0, 1); } try (FileOutputStream out = new FileOutputStream(targetExcelFile)) { workbook.write(out); out.close(); LOG.info("all statistics exported"); } catch (IOException e) { ErrorDialog.openDialog(null, "Could not export the statistics to:\n" + targetExcelFile.getAbsolutePath() + "\n\nPlease verify that you have write access and the file is not opened by any other program!"); LOG.warn("could not write statistics to file", e); } }
From source file:OutputStyles.DiffExcelDefault.java
/** * The output generating class. Creates an excel file at the path indicated * by the String, file//from ww w.j a v a2 s . c o m * @param file The String representation of the output path location * @param skip A string "true or false" value derived from my command line * option interpreter class. */ public void OutputDiffToExcel(String file, String skip) { // Set boolean skip flag if zero values should be avoided if (skip.equals("true")) exclude = true; Workbook wb = new SXSSFWorkbook(1000); // Get the information that we need from the diff file before proceeding TreeSet<String> sampleSet = new TreeSet<>(data.GetRpkmSamples()); TreeSet<String> comparisonSet = new TreeSet<>(data.GetComp()); TreeSet<String> locSet = new TreeSet<>(data.GetCoordLocs()); // Create important styles CreateHeaderStyles(comparisonSet, wb); highlightStyles.put("yellow", HighlightStyle.YellowBoldHighlight(wb)); Sheet sheet = GenerateSheetFromWb(wb); // Create spreadsheet header SetHeaderRow(sheet, sampleSet, comparisonSet); // I think that to minimize the memory overhead, I'm going to have to create // a tab delimited text file and read that to generate the excel workbook String[] base = file.split("\\."); String outTab = base[0] + ".tab"; try (BufferedWriter out = Files.newBufferedWriter(Paths.get(outTab), Charset.defaultCharset())) { CreateTabFileFromData(out, sampleSet, comparisonSet, locSet); // Dereferencing for garbage collection this.data = null; } catch (IOException ex) { ex.printStackTrace(); } try (BufferedReader in = Files.newBufferedReader(Paths.get(outTab), Charset.defaultCharset())) { String line = null; int row = 2; while ((line = in.readLine()) != null) { CreateRowFromTab(line, sampleSet, sheet, row); row++; if (row % 1000 == 0) { System.err.print("[DIFF EXCEL] Finished with row: " + row + "\r"); } } } catch (IOException ex) { Logger.getLogger(DiffExcelDefault.class.getName()).log(Level.SEVERE, null, ex); } System.err.print(System.lineSeparator()); System.err.println("[DIFF EXCEL] Printing to output file!"); /*int row = 2; for(String l : locSet){ CreateRowFromData(sheet, l, sampleSet, comparisonSet, row); row++; }*/ // Freeze the top two panes sheet.createFreezePane(0, 2); try (FileOutputStream out = new FileOutputStream(file)) { wb.write(out); out.close(); } catch (IOException ex) { ex.printStackTrace(); } SXSSFWorkbook b = (SXSSFWorkbook) wb; b.dispose(); }
From source file:pt.webdetails.cda.exporter.CXlsExporter.java
License:Open Source License
public void export(final OutputStream out, final TableModel tableModel) throws ExporterException { // <Template file="testTemplate.xls"> // <RowOffset>3</RowOffset> // <ColumnOffset>2</ColumnOffset> // <WriteColumnNames>true</WriteColumnNames> // </Template> Workbook wb;/*from w w w.j a va 2s . c om*/ InputStream inputStream = null; MetadataTableModel table = (MetadataTableModel) tableModel; Sheet sheet; int ignoreFirstXRows = 0; int rowOffset = 0; int columnOffset = 0; boolean writeColumns = true; boolean templateFound = false; String csvSeperator = ""; int numberOfHeaderRows = 0; if (templateSettings.keySet().size() > 0) { templateFound = true; try { //inputStream = new ClassPathResource(templateSettings.get("filename")).getInputStream(); inputStream = new FileInputStream(templatesDir + templateSettings.get("filename")); wb = new HSSFWorkbook(inputStream); sheet = wb.getSheetAt(0); if (templateSettings.containsKey("RowOffset")) { rowOffset = Integer.parseInt(templateSettings.get("RowOffset")); } if (templateSettings.containsKey("ColumnOffset")) { columnOffset = Integer.parseInt(templateSettings.get("ColumnOffset")); } if (templateSettings.containsKey("WriteColumnNames")) { writeColumns = Boolean.parseBoolean(templateSettings.get("WriteColumnNames")); } if (templateSettings.containsKey("CsvSeperator")) { csvSeperator = "\\" + templateSettings.get("CsvSeperator").toString(); } if (templateSettings.containsKey("WriteFirstXRowsAsHeader")) { numberOfHeaderRows = Integer.parseInt(templateSettings.get("WriteFirstXRowsAsHeader")); } } catch (Exception e) { throw new ExporterException("Error at loading TemplateFile", e); } } else { wb = new HSSFWorkbook(); sheet = wb.createSheet("Sheet1"); } DataFormat cf = wb.createDataFormat(); euroCellStyle = wb.createCellStyle(); euroCellStyle.setDataFormat(cf.getFormat("#,##0.00 \"\"")); doubleCellStyle = wb.createCellStyle(); doubleCellStyle.setDataFormat(cf.getFormat("0.00")); integerCellStyle = wb.createCellStyle(); integerCellStyle.setDataFormat(cf.getFormat("0")); percentCellStyle = wb.createCellStyle(); percentCellStyle.setDataFormat(cf.getFormat("0.00%")); dateCellStyle = wb.createCellStyle(); dateCellStyle.setDataFormat(cf.getFormat("dd.mm.yyyy")); datemonthCellStyle = wb.createCellStyle(); datemonthCellStyle.setDataFormat(cf.getFormat("mm.yyyy")); dateyearCellStyle = wb.createCellStyle(); dateyearCellStyle.setDataFormat(cf.getFormat("yyyy")); dateAndTimeCellStyle = wb.createCellStyle(); dateAndTimeCellStyle.setDataFormat(cf.getFormat("dd.mm.yyyy hh:mm:ss")); boolean interpretCsv = !csvSeperator.equals(""); if (writeColumns) { CellStyle headerCellStyle = null; if (templateFound) headerCellStyle = sheet.getRow(rowOffset).getCell(columnOffset).getCellStyle(); if (numberOfHeaderRows > 0) { ignoreFirstXRows = numberOfHeaderRows; for (int i = 0; i < numberOfHeaderRows; i++) { String[] seperatedRow = new String[0]; int colCount = table.getColumnCount(); if (interpretCsv) { seperatedRow = table.getValueAt(i, 0).toString().split(csvSeperator, -1); colCount = seperatedRow.length; } Row header = sheet.createRow(rowOffset); for (int col = 0; col < colCount; col++) { Cell cell = header.createCell(col + columnOffset); if (templateFound) cell.setCellStyle(headerCellStyle); if (interpretCsv) { cell.setCellValue(seperatedRow[col]); } else { cell.setCellValue(table.getColumnName(col)); } } rowOffset++; } } else { Row header = sheet.createRow(rowOffset); for (int col = 0; col < table.getColumnCount(); col++) { Cell cell = header.createCell(col + columnOffset); if (templateFound) cell.setCellStyle(headerCellStyle); cell.setCellValue(table.getColumnName(col)); } rowOffset++; } sheet.createFreezePane(0, rowOffset); } for (int r = ignoreFirstXRows; r < table.getRowCount(); r++) { CellStyle rowCellStyle = null; // if(templateFound) // try{ // rowCellStyle = sheet.getRow(rowOffset).getCell(columnOffset).getCellStyle(); // }catch (Exception e){} // // int rows = table.getRowCount(); // // Row r1 = sheet.getRow(rowOffset); // // int cols = r1.getLastCellNum(); // // Cell c1 = r1.getCell(columnOffset); Row row = sheet.getRow(r + rowOffset - ignoreFirstXRows); if (row == null) { row = sheet.createRow(r + rowOffset - ignoreFirstXRows); } int colCount; String[] seperatedRow = new String[0]; if (interpretCsv) { seperatedRow = table.getValueAt(r, 0).toString().split(csvSeperator); colCount = seperatedRow.length; } else { colCount = table.getColumnCount(); } for (int col = 0; col < colCount; col++) { Cell cell = null; if (templateFound) { cell = row.getCell(col + columnOffset); if (cell == null) { cell = row.createCell(col + columnOffset); } try { rowCellStyle = sheet.getRow(rowOffset).getCell(col + columnOffset).getCellStyle(); cell.setCellStyle(rowCellStyle); } catch (Exception e) { } } else { cell = row.createCell(col + columnOffset); } if (!interpretCsv) { try { setConvertedValue(cell, table.getValueAt(r, col), col, table); } catch (Exception e) { setConvertedValue(cell, Cell.CELL_TYPE_ERROR, col, table); } } else { setConvertedValue(cell, seperatedRow[col], col, table); } } } try { wb.write(out); } catch (IOException e) { throw new ExporterException("IO Exception converting to utf-8", e); } finally { if (templateSettings.keySet().size() > 0) { try { inputStream.close(); } catch (Exception e) { throw new ExporterException("Error at closing TemplateFile", e); } } } }
From source file:ro.dabuno.office.integration.BusinessPlan.java
License:Apache License
public static void main(String[] args) throws Exception { Workbook wb;/*from w ww .j a v a 2 s.c om*/ if (args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); else 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.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.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(75); //75% scale // Write the output to a file String file = "businessplan.xls"; if (wb instanceof XSSFWorkbook) file += "x"; FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); wb.close(); }
From source file:ru.wmbdiff.ExportIntoExcel.java
License:Apache License
public void export(File file, WMBDiffNoRootTreeTableModel model) { logger.info("export begin"); Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("WMBDiff"); int rowNum = 0; //Create Header CellStyle style;//from w w w . ja v a 2 s .c o m Font headerFont = workbook.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); headerFont.setColor(IndexedColors.WHITE.getIndex()); headerFont.setFontHeightInPoints((short) 10); style = workbook.createCellStyle(); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.WHITE.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.WHITE.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.WHITE.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.WHITE.getIndex()); style.setAlignment(CellStyle.ALIGN_CENTER); style.setFillForegroundColor(IndexedColors.AQUA.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(headerFont); Row row = sheet.createRow(rowNum++); Cell cell; cell = row.createCell(0); cell.setCellValue("Result"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("Broker"); cell.setCellStyle(style); cell = row.createCell(2); cell.setCellValue("Execution Group"); cell.setCellStyle(style); cell = row.createCell(3); cell.setCellValue("Name"); cell.setCellStyle(style); cell = row.createCell(4); cell.setCellValue("Type"); cell.setCellStyle(style); cell = row.createCell(5); cell.setCellValue("Last Modification"); cell.setCellStyle(style); cell = row.createCell(6); cell.setCellValue("Deployment Date"); cell.setCellStyle(style); cell = row.createCell(7); cell.setCellValue("Bar File"); cell.setCellStyle(style); cell = row.createCell(8); cell.setCellValue("Result Description"); cell.setCellStyle(style); sheet.createFreezePane(0, 1); List<DiffExecutionGroup> dEG = model.getDiffExecutionGroupList(); ListIterator<DiffExecutionGroup> litr = dEG.listIterator(); while (litr.hasNext()) { DiffExecutionGroup element = litr.next(); element.getDiffResultList(); ListIterator<DiffDeployedObjectResult> litr2 = element.getDiffResultList().listIterator(); while (litr2.hasNext()) { DiffDeployedObjectResult res = litr2.next(); switch (res.getResult()) { case ONLY_IN_A: createRow(rowNum++, sheet, res.getAObject(), "A", res.getResultDesc()); break; case ONLY_IN_B: createRow(rowNum++, sheet, res.getBObject(), "B", res.getResultDesc()); break; case EQUAL: createRow(rowNum++, sheet, res.getAObject(), "=", res.getResultDesc()); createRow(rowNum++, sheet, res.getBObject(), "=", res.getResultDesc()); sheet.groupRow(rowNum - 2, rowNum - 2); break; case DIFF: createRow(rowNum++, sheet, res.getAObject(), "!=", res.getResultDesc()); createRow(rowNum++, sheet, res.getBObject(), "!=", res.getResultDesc()); sheet.groupRow(rowNum - 2, rowNum - 2); break; } ; } ; } ; //Adjust column width to fit the contents for (int i = 0; i < 9; i++) sheet.autoSizeColumn(i); //set Filter sheet.setAutoFilter(new CellRangeAddress(0, rowNum - 1, 0, 8)); try { FileOutputStream out = new FileOutputStream(file); workbook.write(out); workbook.close(); out.close(); } catch (Exception e) { logger.error("export", e); } logger.info("export end"); }
From source file:utilities.XLSCustomReportsManager.java
License:Open Source License
public void writeOversightDefinition(Connection sd, Connection cResults, int oId, String type, OutputStream outputStream, ReportConfig config, ResourceBundle localisation) throws Exception { boolean isXLSX; if (type != null && type.equals("xls")) { wb = new HSSFWorkbook(); isXLSX = false;/*from www . ja v a2 s.c o m*/ } else { wb = new SXSSFWorkbook(10); isXLSX = true; } Sheet sheet = wb.createSheet("definition"); sheet.createFreezePane(2, 1); Map<String, CellStyle> styles = XLSUtilities.createStyles(wb); ArrayList<Column> cols = getColumnList(localisation); createHeader(cols, sheet, styles); processCustomReportListForXLS(config, sheet, styles, cols); wb.write(outputStream); outputStream.close(); // If XLSX then temporary streaming files need to be deleted if (isXLSX) { ((SXSSFWorkbook) wb).dispose(); } }
From source file:utilities.XLSFormManager.java
License:Open Source License
public void createXLSForm(OutputStream outputStream, Survey survey) throws IOException { this.survey = survey; Sheet surveySheet = wb.createSheet("survey"); Sheet choicesSheet = wb.createSheet("choices"); Sheet settingsSheet = wb.createSheet("settings"); // Freeze panes by default surveySheet.createFreezePane(2, 1); choicesSheet.createFreezePane(3, 1); Map<String, CellStyle> styles = XLSUtilities.createStyles(wb); // Create Columns HashMap<String, Integer> filterIndexes = new HashMap<String, Integer>(); HashMap<String, Integer> namedColumnIndexes = new HashMap<String, Integer>(); HashMap<String, String> addedOptionLists = new HashMap<String, String>(); ArrayList<Column> colsSurvey = getColumnsSurvey(namedColumnIndexes); ArrayList<Column> colsChoices = getColumnsChoices(); ArrayList<Column> colsSettings = getColumnsSettings(); // Write out the column headings createHeader(colsSurvey, surveySheet, styles); createHeader(colsChoices, choicesSheet, styles); createHeader(colsSettings, settingsSheet, styles); // Write out questions Form ff = survey.getFirstForm();//from ww w.j a v a2 s. c o m processFormForXLS(ff, surveySheet, choicesSheet, styles, colsSurvey, colsChoices, filterIndexes, addedOptionLists, namedColumnIndexes); // Write out survey settings processSurveyForXLS(settingsSheet, styles, colsSettings); wb.write(outputStream); outputStream.close(); }
From source file:utilities.XLSTaskManager.java
License:Open Source License
public void createXLSTaskFile(OutputStream outputStream, TaskListGeoJson tl, ResourceBundle localisation, String tz) throws IOException { Sheet taskListSheet = wb.createSheet("tasks"); Sheet taskSettingsSheet = wb.createSheet("settings"); taskListSheet.createFreezePane(5, 1); // Freeze header row and first 5 columns Map<String, CellStyle> styles = XLSUtilities.createStyles(wb); ArrayList<Column> cols = getColumnList(localisation); createHeader(cols, taskListSheet, styles); processTaskListForXLS(tl, taskListSheet, taskSettingsSheet, styles, cols, tz); wb.write(outputStream);/*www . j a v a 2s .c om*/ outputStream.close(); }