/** * Returns the format string, eg $##.##, for the given number format index. * * @param formatIndex the format index * @return the format string */ public String getFormatString(int formatIndex) { String format = null; if (formatIndex >= HSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) { FormatRecord tfr = _customFormatRecords.get(Integer.valueOf(formatIndex)); if (tfr == null) { logger.log(POILogger.ERROR, "Requested format at index " + formatIndex + ", but it wasn't found"); } else { format = tfr.getFormatString(); } } else { format = HSSFDataFormat.getBuiltinFormat((short) formatIndex); } return format; }
@Override public void startExport(List<? extends IExportColumn<?>> columnList) throws Exception { if(m_started) throw new IllegalArgumentException("The writer was already started"); m_started = true; m_columnList = columnList; Workbook wb = m_workbook = createWorkbook(); Font defaultFont = wb.createFont(); defaultFont.setFontHeightInPoints((short) 10); defaultFont.setFontName("Arial"); CellStyle dcs = m_defaultCellStyle = wb.createCellStyle(); dcs.setFont(defaultFont); // FIXME Date format must be locale dependent? CellStyle dates = m_dateStyle = wb.createCellStyle(); dates.setDataFormat(wb.createDataFormat().getFormat("d-m-yyyy")); dates.setFont(defaultFont); CellStyle curs = m_currencyStyle = wb.createCellStyle(); curs.setDataFormat(wb.createDataFormat().getFormat("#,##0.00")); curs.setFont(defaultFont); CellStyle nums = m_numberStyle = wb.createCellStyle(); nums.setDataFormat(wb.createDataFormat().getFormat("#0")); nums.setFont(defaultFont); Font headerFont = wb.createFont(); headerFont.setFontHeightInPoints((short) 10); headerFont.setColor((short) 0xc); headerFont.setBold(true); headerFont.setFontName("Arial"); CellStyle hds = m_headerStyle = wb.createCellStyle(); hds.setBorderBottom(BorderStyle.THIN); hds.setDataFormat(HSSFDataFormat.getBuiltinFormat("text")); hds.setFont(headerFont); createNewSheet(columnList); }
private HSSFCellStyle getHeaderStyle(final int col) { String key = "header-" + col; HSSFCellStyle cs_header = m_styles.get(key); if (cs_header == null) { HSSFFont font_header = getFont(true); cs_header = m_workbook.createCellStyle(); cs_header.setFont(font_header); cs_header.setBorderLeft((short)2); cs_header.setBorderTop((short)2); cs_header.setBorderRight((short)2); cs_header.setBorderBottom((short)2); cs_header.setDataFormat(HSSFDataFormat.getBuiltinFormat("text")); cs_header.setWrapText(true); m_styles.put(key, cs_header); } return cs_header; }
protected void setNumericCell(HSSFCell cell, BigDecimal value, HSSFWorkbook workbook) { if(logger.isDebugEnabled()) logger.debug("setNumericCell(cell={}, value={}, workbook={}) - start", new Object[] {cell, value, workbook} ); cell.setCellValue( ((BigDecimal)value).doubleValue() ); HSSFDataFormat df = workbook.createDataFormat(); int scale = ((BigDecimal)value).scale(); short format; if(scale <= 0){ format = df.getFormat("####"); } else { String zeros = createZeros(((BigDecimal)value).scale()); format = df.getFormat("####." + zeros); } if(logger.isDebugEnabled()) logger.debug("Using format '{}' for value '{}'.", String.valueOf(format), value); HSSFCellStyle cellStyleNumber = workbook.createCellStyle(); cellStyleNumber.setDataFormat(format); cell.setCellStyle(cellStyleNumber); }
private static final void writeCell(final Cell cell, final Object value) { if (value instanceof Number) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(Number.class.cast(value).doubleValue()); } else if (value instanceof Date) { final CellStyle style = cell.getSheet().getWorkbook().createCellStyle(); style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); cell.setCellStyle(style); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(Date.class.cast(value)); } else if (value instanceof Boolean) { cell.setCellType(Cell.CELL_TYPE_BOOLEAN); } else { cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(value != null ? String.valueOf(value) : ""); } }
/** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ @SuppressWarnings("deprecation") public void setCell(int index, Calendar value) { HSSFCell cell = this.row.createCell((short) index); cell.setCellValue(value.getTime()); HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式 cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 设置cell样式为定制的日期格式 cell.setCellStyle(cellStyle); // 设置该cell日期的显示格式 }
/** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ public void setCell(int index, double value) { HSSFCell cell = this.row.createCell((short) index); cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cell.setCellValue(value); HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式 HSSFDataFormat format = workbook.createDataFormat(); cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT)); // 设置cell样式为定制的浮点数格式 cell.setCellStyle(cellStyle); // 设置该cell浮点数的显示格式 }
protected static HSSFCellStyle createDateCellStyle(HSSFWorkbook workbook) { HSSFDataFormat format = workbook.createDataFormat(); short dateFormatCode = format.getFormat(DATE_FORMAT_AS_NUMBER_DBUNIT); HSSFCellStyle dateCellStyle = workbook.createCellStyle(); dateCellStyle.setDataFormat(dateFormatCode); return dateCellStyle; }
/** * We cache the styles; they are expensive to construct. * @param properties props for this run */ public void initCellStyles(TableProperties properties) { // Integer HSSFCellStyle style = getNewCellStyle(); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setDataFormat(HSSFDataFormat.getBuiltinFormat(properties.getProperty(ExcelUtils.EXCEL_FORMAT_INTEGER))); cellStyles.put(STYLE_INTEGER, style); // NUMBER style = getNewCellStyle(); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setDataFormat(HSSFDataFormat.getBuiltinFormat(properties.getProperty(ExcelUtils.EXCEL_FORMAT_NUMBER))); cellStyles.put(STYLE_NUMBER, style); // style = HSSFDataFormat.getBuiltinFormat("0.00%"); // Date style = getNewCellStyle(); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setDataFormat(HSSFDataFormat.getBuiltinFormat(properties.getProperty(ExcelUtils.EXCEL_FORMAT_DATE))); style.setAlignment(CellStyle.ALIGN_RIGHT); cellStyles.put(STYLE_DATE, style); // Long text style = getNewCellStyle(); // http://jakarta.apache.org/poi/hssf/quick-guide.html#NewLinesInCells style.setWrapText(true); cellStyles.put(STYLE_LONGSTRING, style); // Regular text cellStyles.put(STYLE_STRING, getNewCellStyle()); wrapAt = Integer.valueOf(properties.getProperty(ExcelUtils.EXCEL_WRAPAT)); }
private void createWorkbook() { this.workbook = new HSSFWorkbook(); this.dateCellStyle = workbook.createCellStyle(); HSSFDataFormat format = workbook.createDataFormat(); short dateFormat = format.getFormat(getDatePattern()); this.dateCellStyle.setDataFormat(dateFormat); }
private void writeHeaderRow(Entity entity, HSSFSheet sheet) { HSSFRow headerRow = sheet.createRow(0); int colnum = 0; for (Map.Entry<String, Object> component : getComponents(entity)) { String componentName = component.getKey(); headerRow.createCell(colnum).setCellValue(new HSSFRichTextString(componentName)); ComponentDescriptor cd = entity.descriptor().getComponent(componentName); PrimitiveType primitiveType; if (cd.getTypeDescriptor() instanceof SimpleTypeDescriptor) primitiveType = ((SimpleTypeDescriptor) cd.getTypeDescriptor()).getPrimitiveType(); else throw new UnsupportedOperationException("Can only export simple type attributes, " + "failed to export " + entity.type() + '.' + cd.getName()); Class<?> javaType = (primitiveType != null ? primitiveType.getJavaType() : String.class); String formatString = null; if (BeanUtil.isIntegralNumberType(javaType)) formatString = getIntegralPattern(); else if (BeanUtil.isDecimalNumberType(javaType)) formatString = getDecimalPattern(); else if (Time.class.isAssignableFrom(javaType)) formatString = getTimePattern(); else if (Timestamp.class.isAssignableFrom(javaType)) formatString = getTimestampPattern(); else if (Date.class.isAssignableFrom(javaType)) formatString = getDatePattern(); if (formatString != null) { HSSFDataFormat dataFormat = workbook.createDataFormat(); CellStyle columnStyle = workbook.createCellStyle(); columnStyle.setDataFormat(dataFormat.getFormat(formatString)); sheet.setDefaultColumnStyle(colnum, columnStyle); } colnum++; } }
private IStatus storeExcel ( final File file, final List<Event> events, final List<Field> columns, final IProgressMonitor monitor ) throws IOException { final HSSFWorkbook workbook = new HSSFWorkbook (); final HSSFDataFormat dateFormat = workbook.createDataFormat (); final HSSFCellStyle dateCellStyle = workbook.createCellStyle (); dateCellStyle.setDataFormat ( dateFormat.getFormat ( "YYYY-MM-DD hh:mm:ss.000" ) ); try { monitor.beginTask ( Messages.ExportImpl_Progress_ExportingEvents, events.size () + 3 + columns.size () ); try { monitor.subTask ( Messages.ExportImpl_Progress_CreateWorkbook ); monitor.worked ( 1 ); final HSSFSheet sheet = createSheet ( events, workbook, columns ); monitor.worked ( 1 ); monitor.setTaskName ( Messages.ExportImpl_Progress_ExportEvents ); for ( int i = 0; i < events.size (); i++ ) { final HSSFRow row = sheet.createRow ( i + 1 ); final Event e = events.get ( i ); for ( int j = 0; j < columns.size (); j++ ) { final Field field = columns.get ( j ); final ExcelCell cell = new ExcelCell ( row, j, dateCellStyle ); field.render ( e, cell ); } monitor.worked ( 1 ); if ( monitor.isCanceled () ) { return Status.CANCEL_STATUS; } } sheet.setRepeatingRows ( new CellRangeAddress ( 0, 1, -1, -1 ) ); monitor.setTaskName ( "Auto sizing" ); for ( int i = 0; i < columns.size (); i++ ) { monitor.subTask ( String.format ( "Auto sizing column: %s", columns.get ( i ).getHeader () ) ); sheet.autoSizeColumn ( i ); monitor.worked ( 1 ); if ( monitor.isCanceled () ) { return Status.CANCEL_STATUS; } } } finally { monitor.subTask ( Messages.ExportImpl_Progress_CloseFile ); if ( workbook != null ) { makeDocInfo ( workbook ); final FileOutputStream stream = new FileOutputStream ( file ); workbook.write ( stream ); stream.close (); } monitor.worked ( 1 ); } } finally { monitor.done (); } return Status.OK_STATUS; }
private HSSFCellStyle initializeDateCellStyle(HSSFWorkbook workbook, HSSFCellStyle baseStyle) { HSSFCellStyle dateStyle = workbook.createCellStyle(); dateStyle.cloneStyleFrom(baseStyle); dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy")); return dateStyle; }
protected CellStyle buildCellStyle(CellContextData cellContext){ FieldModel field = cellContext.getFieldModel(); String styleString = getStyle(field); String fontString = getFont(field); if(ExcelUtils.isBlank(field.getDataFormat()) && ExcelUtils.isBlank(styleString) && ExcelUtils.isBlank(fontString)){ return null; } if(!ExcelUtils.isBlank(styleString) && styleString.startsWith("#")){ styleString = (String)cellContext.parseValue(styleString); } if(!ExcelUtils.isBlank(field.getDataFormat())){ styleString += ";dataFormat:"+HSSFDataFormat.getBuiltinFormat(field.getDataFormat()); } if(!ExcelUtils.isBlank(fontString) && fontString.startsWith("#")){ fontString = (String)cellContext.parseValue(fontString); } String key = styleString + fontString; CellStyle cstyle = this.styleCache.get(key); if(cstyle!=null){ // System.out.println("get style from cache"); return cstyle; } cstyle = this.generator.getWorkbook().createCellStyle(); BeanWrapper bw = ExcelUtils.newBeanWrapper(cstyle); Map<String, String> styleMap = this.generator.getPropertyStringParser().parseStyle(styleString); try { for(Entry<String, String> entry : styleMap.entrySet()){ /*if(isStaticField(CellStyle.class, entry.getValue())){ Object styleValue = ReflectUtils.getStaticFieldValue(CellStyle.class, getStaticField(entry.getValue())); ReflectUtils.setProperty(cstyle, entry.getKey(), styleValue); }else{ bw.setPropertyValue(entry.getKey(), entry.getValue()); }*/ bw.setPropertyValue(entry.getKey(), getStyleValue(entry.getValue())); } } catch (Exception e) { throw ExcelUtils.wrapAsUnCheckedException(cellContext.getLocation()+" buildCellStyle error: " + e.getMessage(), e); } Font font = buildCellFont(cellContext, fontString); if(font!=null){ cstyle.setFont(font); } this.styleCache.putIfAbsent(key, cstyle); return cstyle; }