List of usage examples for org.apache.poi.ss.usermodel DataFormat getFormat
String getFormat(short index);
From source file:jgnash.convert.exportantur.ssf.AccountExport.java
License:Open Source License
public static void exportAccount(final Account account, final String[] columnNames, final LocalDate startDate, final LocalDate endDate, final File file) { Objects.requireNonNull(account); Objects.requireNonNull(startDate); Objects.requireNonNull(endDate); Objects.requireNonNull(file); Objects.requireNonNull(columnNames); final String extension = FileUtils.getFileExtension(file.getAbsolutePath()); try (final Workbook wb = extension.equals("xlsx") ? new XSSFWorkbook() : new HSSFWorkbook()) { final CreationHelper createHelper = wb.getCreationHelper(); // create a new sheet final Sheet s = wb.createSheet(account.getName()); // create 2 fonts objects final Font defaultFont = wb.createFont(); final Font headerFont = wb.createFont(); defaultFont.setFontHeightInPoints((short) 10); defaultFont.setColor(IndexedColors.BLACK.getIndex()); headerFont.setFontHeightInPoints((short) 11); headerFont.setColor(IndexedColors.BLACK.getIndex()); headerFont.setBold(true);/*from ww w . ja va 2 s .c om*/ // create header cell styles final CellStyle headerStyle = wb.createCellStyle(); // Set the other cell style and formatting headerStyle.setBorderBottom(BorderStyle.THIN); headerStyle.setBorderTop(BorderStyle.THIN); headerStyle.setBorderLeft(BorderStyle.THIN); headerStyle.setBorderRight(BorderStyle.THIN); headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); DataFormat df_header = wb.createDataFormat(); headerStyle.setDataFormat(df_header.getFormat("text")); headerStyle.setFont(headerFont); headerStyle.setAlignment(HorizontalAlignment.CENTER); final CellStyle dateStyle = wb.createCellStyle(); dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("mm/dd/yy")); dateStyle.setFont(defaultFont); final CellStyle timestampStyle = wb.createCellStyle(); timestampStyle.setDataFormat(createHelper.createDataFormat().getFormat("YYYY-MM-DD HH:MM:SS")); timestampStyle.setFont(defaultFont); final CellStyle textStyle = wb.createCellStyle(); textStyle.setFont(defaultFont); final CellStyle amountStyle = wb.createCellStyle(); amountStyle.setFont(defaultFont); amountStyle.setAlignment(HorizontalAlignment.RIGHT); final DecimalFormat format = (DecimalFormat) NumericFormats .getFullCommodityFormat(account.getCurrencyNode()); final String pattern = format.toLocalizedPattern().replace("", account.getCurrencyNode().getPrefix()); final DataFormat df = wb.createDataFormat(); amountStyle.setDataFormat(df.getFormat(pattern)); // Create headers int row = 0; Row r = s.createRow(row); for (int i = 0; i < columnNames.length; i++) { Cell c = r.createCell(i); c.setCellValue(createHelper.createRichTextString(columnNames[i])); c.setCellStyle(headerStyle); } // Dump the transactions for (final Transaction transaction : account.getTransactions(startDate, endDate)) { r = s.createRow(++row); int col = 0; // date Cell c = r.createCell(col, CellType.STRING); c.setCellValue(DateUtils.asDate(transaction.getLocalDate())); c.setCellStyle(dateStyle); // timestamp c = r.createCell(++col, CellType.STRING); c.setCellValue(DateUtils.asDate(transaction.getTimestamp())); c.setCellStyle(timestampStyle); // number c = r.createCell(++col, CellType.STRING); c.setCellValue(transaction.getNumber()); c.setCellStyle(textStyle); // payee c = r.createCell(++col, CellType.STRING); c.setCellValue(transaction.getPayee()); c.setCellStyle(textStyle); // memo c = r.createCell(++col, CellType.STRING); c.setCellValue(transaction.getMemo()); c.setCellStyle(textStyle); // account c = r.createCell(++col, CellType.STRING); c.setCellValue(getAccountColumnValue(transaction, account)); c.setCellStyle(textStyle); // clr, strip any zero width spaces c = r.createCell(++col, CellType.STRING); c.setCellValue(transaction.getReconciled(account).toString().replaceAll(ZERO_WIDTH_SPACE, "")); c.setCellStyle(textStyle); final BigDecimal amount = transaction.getAmount(account); // increase c = r.createCell(++col, CellType.NUMERIC); if (amount.signum() >= 0) { c.setCellValue(amount.doubleValue()); } c.setCellStyle(amountStyle); // decrease c = r.createCell(++col, CellType.NUMERIC); if (amount.signum() < 0) { c.setCellValue(amount.abs().doubleValue()); } c.setCellStyle(amountStyle); // balance c = r.createCell(++col, CellType.NUMERIC); c.setCellValue(account.getBalanceAt(transaction).doubleValue()); c.setCellStyle(amountStyle); } // autosize the column widths final short columnCount = s.getRow(1).getLastCellNum(); // autosize all of the columns + 10 pixels for (int i = 0; i <= columnCount; i++) { s.autoSizeColumn(i); s.setColumnWidth(i, s.getColumnWidth(i) + 10); } Logger.getLogger(AccountExport.class.getName()).log(Level.INFO, "{0} cell styles were used", wb.getNumCellStyles()); // Save final String filename; if (wb instanceof XSSFWorkbook) { filename = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".xlsx"; } else { filename = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".xls"; } try (final OutputStream out = Files.newOutputStream(Paths.get(filename))) { wb.write(out); } catch (final Exception e) { Logger.getLogger(AccountExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e); } } catch (final IOException e) { Logger.getLogger(AccountExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e); } }
From source file:jgnash.convert.exports.ssf.AccountExport.java
License:Open Source License
public static void exportAccount(final Account account, final String[] columnNames, final LocalDate startDate, final LocalDate endDate, final File file) { Objects.requireNonNull(account); Objects.requireNonNull(startDate); Objects.requireNonNull(endDate); Objects.requireNonNull(file); Objects.requireNonNull(columnNames); final String extension = FileUtils.getFileExtension(file.getAbsolutePath()); try (final Workbook wb = extension.equals("xlsx") ? new XSSFWorkbook() : new HSSFWorkbook()) { final CreationHelper createHelper = wb.getCreationHelper(); // create a new sheet final Sheet s = wb.createSheet(account.getName()); // create 2 fonts objects final Font defaultFont = wb.createFont(); final Font headerFont = wb.createFont(); defaultFont.setFontHeightInPoints((short) 10); defaultFont.setColor(IndexedColors.BLACK.getIndex()); headerFont.setFontHeightInPoints((short) 11); headerFont.setColor(IndexedColors.BLACK.getIndex()); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); // create header cell styles final CellStyle headerStyle = wb.createCellStyle(); // Set the other cell style and formatting headerStyle.setBorderBottom(CellStyle.BORDER_THIN); headerStyle.setBorderTop(CellStyle.BORDER_THIN); headerStyle.setBorderLeft(CellStyle.BORDER_THIN); headerStyle.setBorderRight(CellStyle.BORDER_THIN); headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); DataFormat df_header = wb.createDataFormat(); headerStyle.setDataFormat(df_header.getFormat("text")); headerStyle.setFont(headerFont); headerStyle.setAlignment(CellStyle.ALIGN_CENTER); final CellStyle dateStyle = wb.createCellStyle(); dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("mm/dd/yy")); dateStyle.setFont(defaultFont);/* w w w . ja v a2 s . c o m*/ final CellStyle textStyle = wb.createCellStyle(); textStyle.setFont(defaultFont); final CellStyle amountStyle = wb.createCellStyle(); amountStyle.setFont(defaultFont); amountStyle.setAlignment(CellStyle.ALIGN_RIGHT); final DecimalFormat format = (DecimalFormat) CommodityFormat .getFullNumberFormat(account.getCurrencyNode()); final String pattern = format.toLocalizedPattern().replace("", account.getCurrencyNode().getPrefix()); final DataFormat df = wb.createDataFormat(); amountStyle.setDataFormat(df.getFormat(pattern)); // Create headers int row = 0; Row r = s.createRow(row); for (int i = 0; i < columnNames.length; i++) { Cell c = r.createCell(i); c.setCellValue(createHelper.createRichTextString(columnNames[i])); c.setCellStyle(headerStyle); } // Dump the transactions for (final Transaction transaction : account.getTransactions(startDate, endDate)) { r = s.createRow(++row); int col = 0; // date Cell c = r.createCell(col); c.setCellType(Cell.CELL_TYPE_STRING); c.setCellValue(DateUtils.asDate(transaction.getLocalDate())); c.setCellStyle(dateStyle); // number c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_STRING); c.setCellValue(transaction.getNumber()); c.setCellStyle(textStyle); // payee c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_STRING); c.setCellValue(transaction.getPayee()); c.setCellStyle(textStyle); // memo c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_STRING); c.setCellValue(transaction.getMemo()); c.setCellStyle(textStyle); // account c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_STRING); c.setCellValue(getAccountColumnValue(transaction, account)); c.setCellStyle(textStyle); // clr c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_STRING); c.setCellValue(transaction.getReconciled(account).toString()); c.setCellStyle(textStyle); final BigDecimal amount = transaction.getAmount(account); // increase c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_NUMERIC); if (amount.signum() >= 0) { c.setCellValue(amount.doubleValue()); } c.setCellStyle(amountStyle); // decrease c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_NUMERIC); if (amount.signum() < 0) { c.setCellValue(amount.abs().doubleValue()); } c.setCellStyle(amountStyle); // balance c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_NUMERIC); c.setCellValue(account.getBalanceAt(transaction).doubleValue()); c.setCellStyle(amountStyle); } // autosize the column widths final short columnCount = s.getRow(1).getLastCellNum(); // autosize all of the columns + 10 pixels for (int i = 0; i <= columnCount; i++) { s.autoSizeColumn(i); s.setColumnWidth(i, s.getColumnWidth(i) + 10); } Logger.getLogger(AccountExport.class.getName()).log(Level.INFO, "{0} cell styles were used", wb.getNumCellStyles()); // Save final String filename; if (wb instanceof XSSFWorkbook) { filename = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".xlsx"; } else { filename = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".xls"; } try (final FileOutputStream out = new FileOutputStream(filename)) { wb.write(out); } catch (final Exception e) { Logger.getLogger(AccountExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e); } } catch (IOException e) { Logger.getLogger(AccountExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e); } }
From source file:jgnash.engine.budget.BudgetResultsExport.java
License:Open Source License
public static void exportBudgetResultsModel(final File file, final BudgetResultsModel model) { Resource rb = Resource.get(); Workbook wb;/*from w w w . jav a 2 s.c om*/ String extension = FileUtils.getFileExtension(file.getAbsolutePath()); if (extension.equals("xlsx")) { wb = new XSSFWorkbook(); } else { wb = new HSSFWorkbook(); } CreationHelper createHelper = wb.getCreationHelper(); // create a new sheet Sheet s = wb.createSheet(model.getBudget().getName()); // create header cell styles CellStyle headerStyle = wb.createCellStyle(); // create 2 fonts objects Font amountFont = wb.createFont(); Font headerFont = wb.createFont(); amountFont.setFontHeightInPoints((short) 10); amountFont.setColor(IndexedColors.BLACK.getIndex()); headerFont.setFontHeightInPoints((short) 11); headerFont.setColor(IndexedColors.BLACK.getIndex()); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); DataFormat df = wb.createDataFormat(); // Set the other cell style and formatting headerStyle.setBorderBottom(CellStyle.BORDER_THIN); headerStyle.setBorderTop(CellStyle.BORDER_THIN); headerStyle.setBorderLeft(CellStyle.BORDER_THIN); headerStyle.setBorderRight(CellStyle.BORDER_THIN); headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); headerStyle.setDataFormat(df.getFormat("text")); headerStyle.setFont(headerFont); headerStyle.setAlignment(CellStyle.ALIGN_CENTER); int row = 0; Row r = s.createRow(row); // create period headers for (int i = 0; i < model.getDescriptorList().size(); i++) { Cell c = r.createCell(i * 3 + 1); c.setCellValue( createHelper.createRichTextString(model.getDescriptorList().get(i).getPeriodDescription())); c.setCellStyle(headerStyle); s.addMergedRegion(new CellRangeAddress(row, row, i * 3 + 1, i * 3 + 3)); } { int col = model.getDescriptorList().size() * 3 + 1; Cell c = r.createCell(col); c.setCellValue(createHelper.createRichTextString(rb.getString("Title.Summary"))); c.setCellStyle(headerStyle); s.addMergedRegion(new CellRangeAddress(row, row, col, col + 2)); } // create results header columns row++; r = s.createRow(row); { Cell c = r.createCell(0); c.setCellValue(createHelper.createRichTextString(rb.getString("Column.Account"))); c.setCellStyle(headerStyle); for (int i = 0; i <= model.getDescriptorList().size(); i++) { c = r.createCell(i * 3 + 1); c.setCellValue(createHelper.createRichTextString(rb.getString("Column.Budgeted"))); c.setCellStyle(headerStyle); c = r.createCell(i * 3 + 2); c.setCellValue(createHelper.createRichTextString(rb.getString("Column.Change"))); c.setCellStyle(headerStyle); c = r.createCell(i * 3 + 3); c.setCellValue(createHelper.createRichTextString(rb.getString("Column.Remaining"))); c.setCellStyle(headerStyle); } } // must sort the accounts, otherwise child structure is not correct List<Account> accounts = new ArrayList<>(model.getAccounts()); Collections.sort(accounts); // create account rows for (Account account : accounts) { CellStyle amountStyle = wb.createCellStyle(); amountStyle.setFont(amountFont); DecimalFormat format = (DecimalFormat) CommodityFormat.getFullNumberFormat(account.getCurrencyNode()); String pattern = format.toLocalizedPattern().replace("", account.getCurrencyNode().getPrefix()); amountStyle.setDataFormat(df.getFormat(pattern)); row++; int col = 0; r = s.createRow(row); CellStyle cs = wb.createCellStyle(); cs.cloneStyleFrom(headerStyle); cs.setAlignment(CellStyle.ALIGN_LEFT); cs.setIndention((short) (model.getDepth(account) * 2)); Cell c = r.createCell(col); c.setCellValue(createHelper.createRichTextString(account.getName())); c.setCellStyle(cs); List<CellReference> budgetedRefList = new ArrayList<>(); List<CellReference> changeRefList = new ArrayList<>(); List<CellReference> remainingRefList = new ArrayList<>(); for (int i = 0; i < model.getDescriptorList().size(); i++) { BudgetPeriodResults results = model.getResults(model.getDescriptorList().get(i), account); c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_NUMERIC); c.setCellValue(results.getBudgeted().doubleValue()); c.setCellStyle(amountStyle); CellReference budgetedRef = new CellReference(row, col); budgetedRefList.add(budgetedRef); c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_NUMERIC); c.setCellValue(results.getChange().doubleValue()); c.setCellStyle(amountStyle); CellReference changeRef = new CellReference(row, col); changeRefList.add(changeRef); c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_FORMULA); c.setCellStyle(amountStyle); c.setCellFormula(budgetedRef.formatAsString() + "-" + changeRef.formatAsString()); CellReference remainingRef = new CellReference(row, col); remainingRefList.add(remainingRef); } // add summary columns addSummaryCell(r, ++col, budgetedRefList, amountStyle); addSummaryCell(r, ++col, changeRefList, amountStyle); addSummaryCell(r, ++col, remainingRefList, amountStyle); } // add group summary rows for (AccountGroup group : model.getAccountGroupList()) { CellStyle amountStyle = wb.createCellStyle(); amountStyle.setFont(amountFont); amountStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); amountStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); amountStyle.setBorderBottom(CellStyle.BORDER_THIN); amountStyle.setBorderTop(CellStyle.BORDER_THIN); amountStyle.setBorderLeft(CellStyle.BORDER_THIN); amountStyle.setBorderRight(CellStyle.BORDER_THIN); DecimalFormat format = (DecimalFormat) CommodityFormat.getFullNumberFormat(model.getBaseCurrency()); String pattern = format.toLocalizedPattern().replace("", model.getBaseCurrency().getPrefix()); amountStyle.setDataFormat(df.getFormat(pattern)); row++; int col = 0; r = s.createRow(row); CellStyle cs = wb.createCellStyle(); cs.cloneStyleFrom(headerStyle); cs.setAlignment(CellStyle.ALIGN_LEFT); Cell c = r.createCell(col); c.setCellValue(createHelper.createRichTextString(group.toString())); c.setCellStyle(cs); List<CellReference> budgetedRefList = new ArrayList<>(); List<CellReference> changeRefList = new ArrayList<>(); List<CellReference> remainingRefList = new ArrayList<>(); for (int i = 0; i < model.getDescriptorList().size(); i++) { BudgetPeriodResults results = model.getResults(model.getDescriptorList().get(i), group); c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_NUMERIC); c.setCellValue(results.getBudgeted().doubleValue()); c.setCellStyle(amountStyle); CellReference budgetedRef = new CellReference(row, col); budgetedRefList.add(budgetedRef); c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_NUMERIC); c.setCellValue(results.getChange().doubleValue()); c.setCellStyle(amountStyle); CellReference changeRef = new CellReference(row, col); changeRefList.add(changeRef); c = r.createCell(++col); c.setCellType(Cell.CELL_TYPE_FORMULA); c.setCellStyle(amountStyle); c.setCellFormula(budgetedRef.formatAsString() + "-" + changeRef.formatAsString()); CellReference remainingRef = new CellReference(row, col); remainingRefList.add(remainingRef); } // add summary columns addSummaryCell(r, ++col, budgetedRefList, amountStyle); addSummaryCell(r, ++col, changeRefList, amountStyle); addSummaryCell(r, ++col, remainingRefList, amountStyle); } // force evaluation FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); evaluator.evaluateAll(); short columnCount = s.getRow(1).getLastCellNum(); // autosize all of the columns + 10 pixels for (int i = 0; i <= columnCount; i++) { s.autoSizeColumn(i); s.setColumnWidth(i, s.getColumnWidth(i) + 10); } // Save String filename = file.getAbsolutePath(); if (wb instanceof XSSFWorkbook) { filename = FileUtils.stripFileExtension(filename) + ".xlsx"; } else { filename = FileUtils.stripFileExtension(filename) + ".xls"; } try (FileOutputStream out = new FileOutputStream(filename)) { wb.write(out); } catch (Exception e) { Logger.getLogger(BudgetResultsExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e); } }
From source file:me.utils.excel.ExportExcelme.java
License:Open Source License
/** * ?/*from w w w .ja va2s .c o m*/ * @param row * @param column ? * @param val * @param align ??1?23?? * @return ? */ public Cell addCell(Row row, int column, Object val, int align) { Cell cell = row.createCell(column); CellStyle style = styles.get("data" + (align >= 1 && align <= 3 ? align : "")); try { if (val == null) { cell.setCellValue(""); } else if (val instanceof String) { cell.setCellValue((String) val); } else if (val instanceof Integer) { cell.setCellValue((Integer) val); } else if (val instanceof Long) { cell.setCellValue((Long) val); } else if (val instanceof Double) { cell.setCellValue((Double) val); } else if (val instanceof Float) { cell.setCellValue((Float) val); } else if (val instanceof Date) { DataFormat format = wb.createDataFormat(); style.setDataFormat(format.getFormat("yyyy-MM-dd")); cell.setCellValue((Date) val); } else { } } catch (Exception ex) { log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString()); cell.setCellValue(val.toString()); } cell.setCellStyle(style); return cell; }
From source file:net.ceos.project.poi.annotated.core.CellStyleHandler.java
License:Apache License
/** * Apply the data format to the cell style. * // w w w. j ava2 s . c om * @param wb * the {@link Workbook} in use * @param cell * the {@link Cell} to use * @param cs * the cell style * @param formatMask the mask to apply */ protected static void applyDataFormat(final Workbook wb, final Cell cell, final CellStyle cs, final String formatMask) { DataFormat df = dataFormatFactory.newInstance(wb); cs.setDataFormat(df.getFormat(formatMask)); cell.setCellStyle(cs); }
From source file:net.ceos.project.poi.annotated.core.CellStyleHandler.java
License:Apache License
/** * Apply cell style according the one cell style base and format mask. * //w w w .j a v a 2 s .co m * @param configCriteria * the {@link XConfigCriteria} * @param cell * the {@link Cell} * @param cellDecoratorType * the cell decorator by default * @param maskDecoratorType * the format mask by default * @throws ElementException * given when {@link CellStyle} is not defined */ protected static void applyCellStyle(final XConfigCriteria configCriteria, final Cell cell, final String cellDecoratorType, final String maskDecoratorType) throws ElementException { CellStyle cs = configCriteria.getCellStyle(cellDecoratorType); if (maskDecoratorType != null && StringUtils.isNotBlank(configCriteria.getMask(maskDecoratorType)) && cs != null) { /* generate a key based : formatMask + decorator */ String key = configCriteria.generateCellStyleKey(cellDecoratorType, maskDecoratorType); if (!configCriteria.getCellStyleManager().containsKey(key)) { /* clone a cell style */ CellStyle csNew = cloneCellStyle(configCriteria.getWorkbook(), cs); /* initialize/apply a data format */ DataFormat df = dataFormatFactory.newInstance(configCriteria.getWorkbook()); csNew.setDataFormat(df.getFormat(configCriteria.getMask(maskDecoratorType))); configCriteria.getCellStyleManager().put(key, csNew); cs = csNew; } else { cs = configCriteria.getCellStyleManager().get(key); } /* apply cell style to a cell */ cell.setCellStyle(cs); } else { if (cs == null) { /* CASE : if the cell has no cell style base */ cs = cellStyleFactory.newInstance(configCriteria.getWorkbook()); } if (maskDecoratorType != null && StringUtils.isNotBlank(configCriteria.getMask(maskDecoratorType))) { /* CASE : if the cell has a formatMask */ DataFormat df = dataFormatFactory.newInstance(configCriteria.getWorkbook()); cs.setDataFormat(df.getFormat(configCriteria.getMask(maskDecoratorType))); } cell.setCellStyle(cs); } }
From source file:offishell.excel.Excel.java
License:MIT License
/** * <p>//from w w w . ja v a 2 s . c o m * Create {@link Excel} wrapper. * </p> * * @param path * @param book */ private Excel(Path path, XSSFWorkbook book) { this.path = path; this.book = book; this.excel = Locator.file(path); this.sheet = book.getSheetAt(0); this.baseStyle = book.createCellStyle(); this.dateStyle = book.createCellStyle(); CreationHelper helper = book.getCreationHelper(); DataFormat dateFormat = helper.createDataFormat(); Font font = book.createFont(); font.setFontName(" Medium"); font.setFontHeightInPoints((short) 10); baseStyle.setFont(font); baseStyle.setAlignment(HorizontalAlignment.CENTER); baseStyle.setVerticalAlignment(VerticalAlignment.CENTER); baseStyle.setShrinkToFit(true); baseStyle.setWrapText(true); dateStyle.cloneStyleFrom(baseStyle); dateStyle.setDataFormat(dateFormat.getFormat("yyyy/mm/dd")); }
From source file:org.alfresco.repo.web.scripts.datalist.DataListDownloadWebScript.java
License:Open Source License
@Override protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties) throws IOException { NodeRef list = (NodeRef) resource;/*from w w w. j a v a2 s . co m*/ List<NodeRef> items = getItems(list); // Our various formats DataFormat formatter = workbook.createDataFormat(); CellStyle styleInt = workbook.createCellStyle(); styleInt.setDataFormat(formatter.getFormat("0")); CellStyle styleDate = workbook.createCellStyle(); styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd")); CellStyle styleDouble = workbook.createCellStyle(); styleDouble.setDataFormat(formatter.getFormat("General")); CellStyle styleNewLines = workbook.createCellStyle(); styleNewLines.setWrapText(true); // Export the items int rowNum = 1, colNum = 0; for (NodeRef item : items) { Row r = sheet.createRow(rowNum); colNum = 0; for (QName prop : properties) { Cell c = r.createCell(colNum); Serializable val = nodeService.getProperty(item, prop); if (val == null) { // Is it an association, or just missing? List<AssociationRef> assocs = nodeService.getTargetAssocs(item, prop); if (assocs.size() > 0) { StringBuffer text = new StringBuffer(); int lines = 1; for (AssociationRef ref : assocs) { NodeRef child = ref.getTargetRef(); QName type = nodeService.getType(child); if (ContentModel.TYPE_PERSON.equals(type)) { if (text.length() > 0) { text.append('\n'); lines++; } text.append(nodeService.getProperty(child, ContentModel.PROP_USERNAME)); } else if (ContentModel.TYPE_CONTENT.equals(type)) { // TODO Link to the content if (text.length() > 0) { text.append('\n'); lines++; } text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE)); } else { System.err.println("TODO: handle " + type + " for " + child); } } String v = text.toString(); c.setCellValue(v); if (lines > 1) { c.setCellStyle(styleNewLines); r.setHeightInPoints(lines * sheet.getDefaultRowHeightInPoints()); } } else { // This property isn't set c.setCellType(Cell.CELL_TYPE_BLANK); } } else { // Regular property, set if (val instanceof String) { c.setCellValue((String) val); } else if (val instanceof Date) { c.setCellValue((Date) val); c.setCellStyle(styleDate); } else if (val instanceof Integer || val instanceof Long) { double v = 0.0; if (val instanceof Long) v = (double) (Long) val; if (val instanceof Integer) v = (double) (Integer) val; c.setCellValue(v); c.setCellStyle(styleInt); } else if (val instanceof Float || val instanceof Double) { double v = 0.0; if (val instanceof Float) v = (double) (Float) val; if (val instanceof Double) v = (double) (Double) val; c.setCellValue(v); c.setCellStyle(styleDouble); } else { // TODO System.err.println("TODO: handle " + val.getClass().getName() + " - " + val); } } colNum++; } rowNum++; } // Sensible column widths please! colNum = 0; for (QName prop : properties) { sheet.autoSizeColumn(colNum); colNum++; } }
From source file:org.beangle.commons.transfer.excel.PoiTest.java
License:Open Source License
public static void main(String[] args) throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("new sheet"); // Create a row and put some cells in it. Rows are 0 based. HSSFRow row = sheet.createRow(0);/*from w w w. j av a2s. c om*/ // Create a cell and put a date value in it. The first cell is not // styled as a date. HSSFCell cell = row.createCell(0); cell.setCellValue(new Date()); // we style the second cell as a date (and time). It is important to // create a new cell style from the workbook // otherwise you can end up modifying the built in style and effecting // not only this cell but other cells. HSSFCellStyle cellStyle = wb.createCellStyle(); DataFormat df = wb.createDataFormat(); // cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); cellStyle.setDataFormat(df.getFormat("YYYY-MM-DD HH:MM:SS")); cell = row.createCell(1); cell.setCellValue(new Date()); cell.setCellStyle(cellStyle); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("src/test/resources/workbook.xls"); wb.write(fileOut); fileOut.close(); }
From source file:org.dbflute.helper.io.xls.DfTableXlsWriter.java
License:Apache License
public DfTableXlsWriter(File file) { _out = create(file);/*ww w . j av a2 s .c om*/ _workbook = DfXlsFactory.instance().createWorkbook(file); final DataFormat dataFormat = _workbook.createDataFormat(); _dateStyle = _workbook.createCellStyle(); _dateStyle.setDataFormat(dataFormat.getFormat(DATE_FORMAT)); _base64Style = _workbook.createCellStyle(); _base64Style.setDataFormat(dataFormat.getFormat(BASE64_FORMAT)); }