CellStyle createHeadDateStyle() { if (headDateCellStyle != null) { return headDateCellStyle; } CellStyle cellStyle = wb.createCellStyle(); DataFormat format = wb.createDataFormat(); cellStyle.setDataFormat(format.getFormat("m/d/yy h:mm")); // 设置这些样式 cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index); cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 生成一个字体 Font font = wb.createFont(); font.setColor(IndexedColors.BLACK.index); font.setFontHeightInPoints((short) 12); font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 把字体应用到当前的样式 cellStyle.setFont(font); headDateCellStyle = cellStyle; return cellStyle; }
/** * 小数格式 * * @return CellStyle */ public CellStyle getDecimalStyle() { if (buildInStyleMap.containsKey(DECIMAL_STYLE_KEY)) { return buildInStyleMap.get(DECIMAL_STYLE_KEY); } CellStyle decimalStyle = workbook.createCellStyle();//小数样式 if (!buildInFormatMap.containsKey(DATA_FORMAT_KEY)) { DataFormat dataFormat = workbook.createDataFormat(); buildInFormatMap.put(DATA_FORMAT_KEY, dataFormat); } decimalStyle.setDataFormat(buildInFormatMap.get(DATA_FORMAT_KEY).getFormat("0.00")); this.setCommonStyle(decimalStyle); buildInStyleMap.put(DECIMAL_STYLE_KEY, decimalStyle); return decimalStyle; }
/** * 日期样式 yyyy-MM-dd HH:mm * * @return CellStyle */ public CellStyle getDateStyle() { if (buildInStyleMap.containsKey(DATE_STYLE_KEY)) { return buildInStyleMap.get(DATE_STYLE_KEY); } CellStyle dateStyle = workbook.createCellStyle();//日期样式 if (!buildInFormatMap.containsKey(DATA_FORMAT_KEY)) { DataFormat dataFormat = workbook.createDataFormat(); buildInFormatMap.put(DATA_FORMAT_KEY, dataFormat); } dateStyle.setDataFormat(buildInFormatMap.get(DATA_FORMAT_KEY).getFormat("yyyy-MM-dd HH:mm")); this.setCommonStyle(dateStyle); buildInStyleMap.put(DATE_STYLE_KEY, dateStyle); return dateStyle; }
/** * 日期样式 yyyy/MM/dd * * @return CellStyle */ public CellStyle getDate8Style() { if (buildInStyleMap.containsKey(DATE_8_STYLE_KEY)) { return buildInStyleMap.get(DATE_8_STYLE_KEY); } CellStyle date8Style = workbook.createCellStyle();//年月日样式 if (!buildInFormatMap.containsKey(DATA_FORMAT_KEY)) { DataFormat dataFormat = workbook.createDataFormat(); buildInFormatMap.put(DATA_FORMAT_KEY, dataFormat); } date8Style.setDataFormat(buildInFormatMap.get(DATA_FORMAT_KEY).getFormat("yyyy/MM/dd")); this.setCommonStyle(date8Style); buildInStyleMap.put(DATE_8_STYLE_KEY, date8Style); return date8Style; }
/** * 根据格式,创建返回样式对象 * * @param format 格式 * @return 样式对象 */ public CellStyle getCustomFormatStyle(String format) { //存在对应格式直接返回 if (customFormatStyleMap.containsKey(format)) { return customFormatStyleMap.get(format); } CellStyle customDateStyle = workbook.createCellStyle(); if (!buildInFormatMap.containsKey(DATA_FORMAT_KEY)) { DataFormat dataFormat = workbook.createDataFormat(); buildInFormatMap.put(DATA_FORMAT_KEY, dataFormat); } customDateStyle.setDataFormat(buildInFormatMap.get(DATA_FORMAT_KEY).getFormat(format)); this.setCommonStyle(customDateStyle); //放入map缓存 customFormatStyleMap.put(format, customDateStyle); return customDateStyle; }
public CellStyle getDateStyle() { CellStyle dateStyle = workbook.createCellStyle(); // 设置单元格居中对齐 dateStyle.setAlignment(CellStyle.ALIGN_CENTER); // 设置单元格垂直居中对齐 dateStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); DataFormat format = workbook.createDataFormat(); dateStyle.setDataFormat(format.getFormat("yyyy-MM-dd HH:mm")); // 创建单元格内容显示不下时自动换行 dateStyle.setWrapText(true); // 设置单元格字体样式 Font font = workbook.createFont(); // 设置字体加粗 font.setBoldweight(Font.BOLDWEIGHT_BOLD); font.setFontName("宋体"); font.setFontHeight((short) 200); dateStyle.setFont(font); setBorder(dateStyle); return dateStyle; }
protected void addRow(HSSFWorkbook workbook, HSSFSheet sheet, Object value, int row, int column) { HSSFRow hssfRow = sheet.getRow(row); hssfRow = (hssfRow == null) ? sheet.createRow(row) : hssfRow; HSSFCell cell = hssfRow.getCell(column); cell = (cell == null) ? hssfRow.createCell(column) : cell; String cellValue = (value == null) ? "" : value.toString(); DecimalFormat decimalFormatter = new DecimalFormat("###,###,###,##0.00"); try { double doubleValue = decimalFormatter.parse(cellValue).doubleValue(); DataFormat dataFormat = workbook.createDataFormat(); HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(dataFormat.getFormat("###,###,###,##0.00")); cell.setCellValue(doubleValue); } catch (ParseException e) { cell.setCellValue(cellValue); } formatCell(workbook, cell); }
protected static void setCellValue(Workbook wb, Cell cell, Object value) { if (cell == null) { return; } if (value instanceof Boolean) { cell.setCellValue((Boolean)value); } else if (value instanceof Number) { cell.setCellValue(((Number)value).doubleValue()); } else if (value instanceof Date) { CellStyle cellStyle = wb.createCellStyle(); DataFormat poiFormat = wb.createDataFormat(); // Format: 0x16, "m/d/yy h:mm" final short format = poiFormat.getFormat(BuiltinFormats.getBuiltinFormat(0x16)); cellStyle.setDataFormat(format); cell.setCellValue(((Date)value)); cell.setCellStyle(cellStyle); } else if (value instanceof Calendar) { cell.setCellValue(((Calendar)value)); } else if (value != null) { cell.setCellValue(value.toString()); } else { cell.setCellValue(""); cell.setCellType(Cell.CELL_TYPE_BLANK); } }
/** * 添加一个单元格 * @param row 添加的行 * @param column 添加列号 * @param val 添加值 * @param align 对齐方式(1:靠左;2:居中;3:靠右) * @return 单元格对象 */ public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){ 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 { if (fieldType != Class.class){ cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val)); }else{ cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), "fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val)); } } } catch (Exception ex) { log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString()); cell.setCellValue(val.toString()); } cell.setCellStyle(style); return cell; }
ExcelTestHelper(final String parent, boolean generateXls) throws Exception { this.xls = generateXls; // Create a test Excel sheet with all types of supported data Workbook wb = generateXls ? new HSSFWorkbook() : new XSSFWorkbook(); CreationHelper creationHelper = wb.getCreationHelper(); DataFormat dataFormat = creationHelper.createDataFormat(); short fmt = dataFormat.getFormat("yyyy-mm-dd hh:mm:ss"); CellStyle style = wb.createCellStyle(); style.setDataFormat(fmt); Sheet sheetWithHeader = wb.createSheet("Sheet 1"); // Create header row Row headerRow = sheetWithHeader.createRow((short) 0); headerRow.createCell(0).setCellValue("Number"); headerRow.createCell(1).setCellValue("String1"); headerRow.createCell(2).setCellValue("String2"); headerRow.createCell(3).setCellValue("MyTime"); headerRow.createCell(4).setCellValue("Formula"); headerRow.createCell(5).setCellValue("Boolean"); headerRow.createCell(6).setCellValue("Error"); generateSheetData(sheetWithHeader, style, (short)1); Sheet sheetWithoutHeader = wb.createSheet("Sheet 2"); generateSheetData(sheetWithoutHeader, style, (short)0); testFilePath = new File(parent, "excelTestFile").getPath(); // Write the output to a file FileOutputStream fileOut = new FileOutputStream(testFilePath); wb.write(fileOut); fileOut.close(); }
CellStyle createDateStyle() { if (dateCellStyle != null) { return dateCellStyle; } CellStyle cellStyle = wb.createCellStyle(); DataFormat format = wb.createDataFormat(); cellStyle.setDataFormat(format.getFormat("m/d/yy h:mm")); dateCellStyle = cellStyle; return cellStyle; }
@Override public String getFormatPattern() { final DataFormat dataFormat = cell.getSheet().getWorkbook().createDataFormat(); final short formatIndex = getFormatIndex(); String formatPattern = dataFormat.getFormat(formatIndex); if(formatPattern == null) { formatPattern = ""; } return formatPattern; }
private void setStyles() { csNormal = wb.createCellStyle(); csUeberschrift = wb.createCellStyle(); csTitel = wb.createCellStyle(); DataFormat dataFormat = wb.createDataFormat(); // Schriftart Schüler Font fNormal = wb.createFont(); fNormal.setFontHeightInPoints((short) 10); // Schriftgröße auf 10pt setzen fNormal.setColor(Font.COLOR_NORMAL); // Schriftfarbe schwarz fNormal.setBoldweight(Font.BOLDWEIGHT_NORMAL); // CellStyle für Schüler csNormal.setFont(fNormal); // Schriftart csNormal.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csNormal.setBorderBottom(CellStyle.BORDER_THIN); // Umrandung unten einschalten csNormal.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung unten in schwarz csNormal.setBorderLeft(CellStyle.BORDER_THIN); // Umrandung links einschalten csNormal.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung links in schwarz csNormal.setBorderTop(CellStyle.BORDER_THIN); // Umrandung oben einschalten csNormal.setTopBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung oben in schwarz csNormal.setBorderRight(CellStyle.BORDER_THIN); // Umrandung rechts einschalten csNormal.setRightBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung rechts in schwarz csNormal.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text // Fett Font fUeberschrift = wb.createFont(); fUeberschrift.setFontHeightInPoints((short) 11); fUeberschrift.setColor(Font.COLOR_NORMAL); fUeberschrift.setBoldweight(Font.BOLDWEIGHT_BOLD); csUeberschrift.setFont(fUeberschrift); csUeberschrift.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csUeberschrift.setBorderBottom(CellStyle.BORDER_THIN); // Umrandung unten einschalten csUeberschrift.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung unten in schwarz csUeberschrift.setBorderLeft(CellStyle.BORDER_THIN); // Umrandung links einschalten csUeberschrift.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung links in schwarz csUeberschrift.setBorderTop(CellStyle.BORDER_THIN); // Umrandung oben einschalten csUeberschrift.setTopBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung oben in schwarz csUeberschrift.setBorderRight(CellStyle.BORDER_THIN); // Umrandung rechts einschalten csUeberschrift.setRightBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung rechts in schwarz csUeberschrift.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text // Schriftart für Titel Font fTitel = wb.createFont(); fTitel.setFontHeightInPoints((short) 24); // größe 24pt fTitel.setColor(Font.COLOR_NORMAL); // schwarz fTitel.setBoldweight(Font.BOLDWEIGHT_BOLD); // fett // CellStyle für den Titel csTitel.setFont(fTitel); // Schrift setzen csTitel.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csTitel.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text }
private void setStyles() { csSpieleEtc = wb.createCellStyle(); // Stil für Spiele, Schiris, Zeiten etc. csTitel = wb.createCellStyle(); // Stil für Titel csUntertitel = wb.createCellStyle(); // Stil für Untertitel csTabellenueberschrift = wb.createCellStyle(); // Stil für die Tabellenüberschriften (wie für Spiele, nur fett) DataFormat dataFormat = wb.createDataFormat(); // Um das Datenformat auf Text zu setzen // Schriftart für Titel Font fTitel = wb.createFont(); fTitel.setFontHeightInPoints((short) 24); // größe 24pt fTitel.setColor(Font.COLOR_NORMAL); // schwarz fTitel.setBoldweight(Font.BOLDWEIGHT_BOLD); // fett // CellStyle für den Titel csTitel.setFont(fTitel); // Schrift setzen csTitel.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csTitel.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text // Schriftart für den Untertitel Font fUntertitel = wb.createFont(); fUntertitel.setFontHeightInPoints((short) 10); // Schriftgröße auf 10pt setzen fUntertitel.setColor(Font.COLOR_NORMAL); // Schriftfarbe schwarz fUntertitel.setBoldweight(Font.BOLDWEIGHT_NORMAL); // CellStyle für den Untertitel csUntertitel.setFont(fUntertitel); // Schriftart csUntertitel.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csUntertitel.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text // Schriftart für Tabellenüberschriften Font fTabellenueberschrift = wb.createFont(); fTabellenueberschrift.setFontHeightInPoints((short) 11); // größe 11pt fTabellenueberschrift.setColor(Font.COLOR_NORMAL); // schwarz fTabellenueberschrift.setBoldweight(Font.BOLDWEIGHT_BOLD); // fett // CellStyle für die Tabellenüberschriften csTabellenueberschrift.setFont(fTabellenueberschrift); // Schriftart csTabellenueberschrift.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csTabellenueberschrift.setBorderBottom(CellStyle.BORDER_THIN); // Umrandung unten einschalten csTabellenueberschrift.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung unten in schwarz csTabellenueberschrift.setBorderLeft(CellStyle.BORDER_THIN); // Umrandung links einschalten csTabellenueberschrift.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung links in schwarz csTabellenueberschrift.setBorderTop(CellStyle.BORDER_THIN); // Umrandung oben einschalten csTabellenueberschrift.setTopBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung oben in schwarz csTabellenueberschrift.setBorderRight(CellStyle.BORDER_THIN); // Umrandung rechts einschalten csTabellenueberschrift.setRightBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung rechts in schwarz csTabellenueberschrift.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text // Schriftart für Spiele, Schiris, Zeiten etc. Font fSpieleEtc = wb.createFont(); fSpieleEtc.setFontHeightInPoints((short) 10); // Schriftgröße auf 10pt setzen fSpieleEtc.setColor(Font.COLOR_NORMAL); // Schriftfarbe schwarz fSpieleEtc.setBoldweight(Font.BOLDWEIGHT_NORMAL); // CellStyle für Spiele, Schiris, Zeiten etc. csSpieleEtc.setFont(fSpieleEtc); // Schriftart csSpieleEtc.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csSpieleEtc.setBorderBottom(CellStyle.BORDER_THIN); // Umrandung unten einschalten csSpieleEtc.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung unten in schwarz csSpieleEtc.setBorderLeft(CellStyle.BORDER_THIN); // Umrandung links einschalten csSpieleEtc.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung links in schwarz csSpieleEtc.setBorderTop(CellStyle.BORDER_THIN); // Umrandung oben einschalten csSpieleEtc.setTopBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung oben in schwarz csSpieleEtc.setBorderRight(CellStyle.BORDER_THIN); // Umrandung rechts einschalten csSpieleEtc.setRightBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung rechts in schwarz csSpieleEtc.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text }
private void setStyles() { csTitel = wb.createCellStyle(); csUntertitel = wb.createCellStyle(); csTabelleFett = wb.createCellStyle(); csTabelleNormal = wb.createCellStyle(); DataFormat dataFormat = wb.createDataFormat(); // Um das Datenformat auf Text zu setzen // Schriftart für Titel Font fTitel = wb.createFont(); fTitel.setFontHeightInPoints((short) 24); // größe 24pt fTitel.setColor(Font.COLOR_NORMAL); // schwarz fTitel.setBoldweight(Font.BOLDWEIGHT_BOLD); // fett // CellStyle für den Titel csTitel.setFont(fTitel); // Schrift setzen csTitel.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csTitel.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text // Schriftart für den Untertitel Font fUntertitel = wb.createFont(); fUntertitel.setFontHeightInPoints((short) 10); // Schriftgröße auf 10pt setzen fUntertitel.setColor(Font.COLOR_NORMAL); // Schriftfarbe schwarz fUntertitel.setBoldweight(Font.BOLDWEIGHT_NORMAL); // CellStyle für den Untertitel csUntertitel.setFont(fUntertitel); // Schriftart csUntertitel.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csUntertitel.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text // Schriftart für Tabellenüberschriften Font fTabelleFett = wb.createFont(); fTabelleFett.setFontHeightInPoints((short) 10); // größe 11pt fTabelleFett.setColor(Font.COLOR_NORMAL); // schwarz fTabelleFett.setBoldweight(Font.BOLDWEIGHT_BOLD); // fett // CellStyle für die Tabellenüberschriften csTabelleFett.setFont(fTabelleFett); // Schriftart csTabelleFett.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // Mittige Anordnung csTabelleFett.setAlignment(CellStyle.ALIGN_CENTER); csTabelleFett.setBorderBottom(CellStyle.BORDER_THIN); // Umrandung unten einschalten csTabelleFett.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung unten in schwarz csTabelleFett.setBorderLeft(CellStyle.BORDER_THIN); // Umrandung links einschalten csTabelleFett.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung links in schwarz csTabelleFett.setBorderTop(CellStyle.BORDER_THIN); // Umrandung oben einschalten csTabelleFett.setTopBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung oben in schwarz csTabelleFett.setBorderRight(CellStyle.BORDER_THIN); // Umrandung rechts einschalten csTabelleFett.setRightBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung rechts in schwarz csTabelleFett.setDataFormat(dataFormat.getFormat("text")); // Datenformat Text // Schriftart für Spiele, Schiris, Zeiten etc. Font fTabelleNormal = wb.createFont(); fTabelleNormal.setFontHeightInPoints((short) 10); // Schriftgröße auf 10pt setzen fTabelleNormal.setColor(Font.COLOR_NORMAL); // Schriftfarbe schwarz fTabelleNormal.setBoldweight(Font.BOLDWEIGHT_NORMAL); // CellStyle für Spiele, Schiris, Zeiten etc. csTabelleNormal.cloneStyleFrom(csTabelleFett); csTabelleNormal.setFont(fTabelleNormal); // Schriftart }
private void setStyles() { csNormal1 = wb.createCellStyle(); // Stil für Uhrzeiten, Namen etc. (gerade Spiele) csNormal2 = wb.createCellStyle(); // ungerade Spiele csInfos = wb.createCellStyle(); // Stil für Infos über der eigentlichen Liste csUeberschriften = wb.createCellStyle(); // Stil für Überschriften DataFormat dataFormat = wb.createDataFormat(); // Textformat in den Zellen // Schriftart für Überschriften Font fUeberschriften = wb.createFont(); fUeberschriften.setFontHeightInPoints((short) 11); // 12pt fUeberschriften.setColor(Font.COLOR_NORMAL); // schwarz fUeberschriften.setBoldweight(Font.BOLDWEIGHT_BOLD); // fett // CellStyle für Überschriften csUeberschriften.setFont(fUeberschriften); csUeberschriften.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // zentrieren csUeberschriften.setVerticalAlignment(CellStyle.VERTICAL_CENTER); csUeberschriften.setBorderBottom(CellStyle.BORDER_THIN); // Umrandung unten einschalten csUeberschriften.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung unten in schwarz csUeberschriften.setBorderLeft(CellStyle.BORDER_THIN); // Umrandung links einschalten csUeberschriften.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung links in schwarz csUeberschriften.setBorderTop(CellStyle.BORDER_THIN); // Umrandung oben einschalten csUeberschriften.setTopBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung oben in schwarz csUeberschriften.setBorderRight(CellStyle.BORDER_THIN); // Umrandung rechts einschalten csUeberschriften.setRightBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung rechts in schwarz csUeberschriften.setDataFormat(dataFormat.getFormat("text")); // als Text formatiert // Schriftart für Infos am Anfang Font fInfos = wb.createFont(); fInfos.setFontHeightInPoints((short) 11); // 11pt fInfos.setColor(Font.COLOR_NORMAL); // schwarz fInfos.setBoldweight(Font.BOLDWEIGHT_BOLD); // CellStyle für Infos csInfos.setFont(fInfos); csInfos.setAlignment(CellStyle.ALIGN_CENTER_SELECTION); // zentriert csInfos.setVerticalAlignment(CellStyle.VERTICAL_CENTER); csInfos.setDataFormat(dataFormat.getFormat("text")); // text // Schriftart für normales Font fNormal = wb.createFont(); fNormal.setFontHeightInPoints((short) 10); // 11pt fNormal.setColor(Font.COLOR_NORMAL); fNormal.setBoldweight(Font.BOLDWEIGHT_NORMAL); // CellStyle normal csNormal1.setFont(fNormal); csNormal1.setAlignment(CellStyle.ALIGN_LEFT); // linksbündig csNormal1.setVerticalAlignment(CellStyle.VERTICAL_CENTER); csNormal1.setBorderBottom(CellStyle.BORDER_THIN); // Umrandung unten einschalten csNormal1.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung unten in schwarz csNormal1.setBorderLeft(CellStyle.BORDER_THIN); // Umrandung links einschalten csNormal1.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung links in schwarz csNormal1.setBorderTop(CellStyle.BORDER_THIN); // Umrandung oben einschalten csNormal1.setTopBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung oben in schwarz csNormal1.setBorderRight(CellStyle.BORDER_THIN); // Umrandung rechts einschalten csNormal1.setRightBorderColor(IndexedColors.BLACK.getIndex()); // Umrandung rechts in schwarz csNormal1.setDataFormat(dataFormat.getFormat("text")); csNormal2.cloneStyleFrom(csNormal1); // Gleich wie Normal für Gerade, nur der Hintergrund ist anders csNormal2.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // leicht grau csNormal2.setFillPattern(CellStyle.SOLID_FOREGROUND); }
/** * 添加一个单元格 * * @param row * 添加的行 * @param column * 添加列号 * @param val * 添加值 * @param align * 对齐方式 * @return 单元格对象 */ public Cell addCell(Row row, int column, Object val, ExAlign align) { Cell cell = row.createCell(column); CellStyle style = styles.get("data" + align.getValue()); 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 { throw new RuntimeException("value is unkown class type"); } } catch (Exception ex) { log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString()); cell.setCellValue(val.toString()); } cell.setCellStyle(style); return cell; }
/** * Apply a BIRT number/date/time format to a POI CellStyle. * @param workbook * The workbook containing the CellStyle (needed to create a new DataFormat). * @param birtStyle * The BIRT style which may contain a number format. * @param poiStyle * The CellStyle that is to receive the number format. */ public void applyNumberFormat(Workbook workbook, BirtStyle birtStyle, CellStyle poiStyle, Locale locale) { String dataFormat = null; String format = getNumberFormat(birtStyle); if( format != null ) { log.debug( "BIRT number format == ", format); dataFormat = poiNumberFormatFromBirt(format); } else { format = getDateTimeFormat(birtStyle); if( format != null ) { log.debug( "BIRT date/time format == ", format ); dataFormat = poiDateTimeFormatFromBirt( format, locale ); } else { format = getTimeFormat(birtStyle); if( format != null ) { log.debug( "BIRT time format == ", format ); dataFormat = poiDateTimeFormatFromBirt( format, locale ); } else { format = getDateFormat(birtStyle); if( format != null ) { log.debug( "BIRT date format == ", format ); dataFormat = poiDateTimeFormatFromBirt( format, locale ); } } } } if( dataFormat != null ) { DataFormat poiFormat = workbook.createDataFormat(); log.debug( "Setting POI data format to ", dataFormat); poiStyle.setDataFormat(poiFormat.getFormat(dataFormat)); } }
public void initialize() throws IOException{ File directory = new File( "." ); fileExists = false; for( File f : directory.listFiles() ) { if( f.getName().equals( workBookName ) ) { fileExists = true; break; } } File workBookFile = new File(workBookName); if(!fileExists){ workBookFile.createNewFile(); wb = new HSSFWorkbook(); }else{ //in = ; wb = new HSSFWorkbook(new FileInputStream(workBookFile)); } // create a new workbook out = new FileOutputStream(workBookName); DataFormat df = wb.createDataFormat(); for(int i = 0 ; i < datatypes.length ; i++){ cellTypes[i] = wb.createCellStyle(); cellTypes[i].setDataFormat(df.getFormat(datatypes[i])); } }
/** * Set specified cell format * * @param excelFieldFormat the specified format * @param cell the cell to set up format */ private void setDataFormat( String excelFieldFormat, Cell cell ) { if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "ExcelWriterStep.Log.SetDataFormat", excelFieldFormat, CellReference .convertNumToColString( cell.getColumnIndex() ), cell.getRowIndex() ) ); } DataFormat format = data.wb.createDataFormat(); short formatIndex = format.getFormat( excelFieldFormat ); CellStyle style = data.wb.createCellStyle(); style.cloneStyleFrom( cell.getCellStyle() ); style.setDataFormat( formatIndex ); cell.setCellStyle( style ); }
private int buildGridExcelData(ReportGrid gridModel, Sheet sheet, int starDataRow, Map<String, CellStyle> styles) { CellStyle dataAlignLeftStyle = styles.get(GridStyleType.dataAlignLeftStyle.name()); CellStyle dataAlignCenterStyle = styles.get(GridStyleType.dataAlignCenterStyle.name()); CellStyle dataAlignRightStyle = styles.get(GridStyleType.dataAlignRightStyle.name()); IFillCellInterceptor interceptor = ContextHolder.getBean(IFillCellInterceptor.BEAN_ID); List<ReportGridHeader> bottomGridExcelHeader = new ArrayList<ReportGridHeader>(); this.calculateBottomColumnHeader(gridModel.getGridHeaderModelList(), bottomGridExcelHeader); List<Map<String, Object>> excelDatas = gridModel.getGridDataModel().getDatas(); String treeColumn = gridModel.getGridDataModel().getTreeColumn(); int excelDataIndex = 0; int rowSize = excelDatas.size(); Cell cell; Row row; for (int rowNum = starDataRow; rowNum <= starDataRow + rowSize - 1; rowNum++) { row = sheet.createRow(rowNum); Map<String, Object> map = excelDatas.get(excelDataIndex); int j = 0; for (ReportGridHeader header : bottomGridExcelHeader) { Object value = map.get(header.getColumnName()); int dataAlign = header.getDataAlign(); cell = row.createCell(j); if (dataAlign == 1) { cell.setCellStyle(dataAlignCenterStyle); } else if (dataAlign == 2) { cell.setCellStyle(dataAlignRightStyle); } else { cell.setCellStyle(dataAlignLeftStyle); } if (value != null) { if (header.getColumnName().equalsIgnoreCase(treeColumn)) { int level = this.calculateIndentationCount(value.toString()); cell.setCellStyle(new GridStyleBuilder().createIndentationCellStyle(sheet.getWorkbook(), level == 0 ? 0 : level * 2)); cell.setCellValue(value.toString()); } else { if (value instanceof BigDecimal || value instanceof Float || value instanceof Double){ CellStyle style = cell.getCellStyle(); DataFormat format = sheet.getWorkbook().createDataFormat(); String displayFormat = header.getDisplayFormat(); if (StringUtils.isEmpty(displayFormat)) style.setDataFormat(format.getFormat("#,##0.00")); else style.setDataFormat(format.getFormat(displayFormat)); cell.setCellStyle(style); } interceptor.fillCellValue(sheet, row, cell, value); } } else { cell.setCellValue(""); } sheet.setColumnWidth(cell.getColumnIndex(), header.getWidth() / 6 > 255 ? 254 * 256 : header.getWidth() / 6 * 256); j++; } excelDataIndex++; } return starDataRow + rowSize; }
private void execute(final Sheet sheet) { DataFormat format = sheet.getWorkbook().createDataFormat(); for(int i=0; i <= 59; i++) { final Row row = sheet.getRow(3 + i); Cell descriptionCell = row.getCell(1); Cell testCaseCell = row.getCell(2); Cell testResultCell = row.getCell(3); Cell indexCell = row.getCell(4); Cell formatCell = row.getCell(5); descriptionCell.setCellValue(String.format("[10進数]=%d, [16進数]=%s", i, Integer.toHexString(i))); // テストケースのスタイルの設定 CellStyle style = sheet.getWorkbook().createCellStyle(); style.setDataFormat((short)i); style.setBorderBottom(CellStyle.BORDER_THIN); testCaseCell.setCellStyle(style); if(i == 0) { testCaseCell.setCellValue("テキスト"); } else if(range(i, 1, 8)) { // 数値 testCaseCell.setCellValue(-123.456); } else if(range(i, 9, 11)) { // パーセント、小数 testCaseCell.setCellValue(0.0123); } else if(range(i, 12, 13)) { // 分数 testCaseCell.setCellValue(12.345); } else if(range(i, 14, 36)) { // 日時 testCaseCell.setCellValue(Timestamp.valueOf("2000-02-29 10:19:23.123")); } else if(range(i, 37, 44)) { // 会計 testCaseCell.setCellValue(-123.456); } else if(range(i, 45, 48)) { // 時間、経過時間 testCaseCell.setCellValue(Timestamp.valueOf("1900-01-01 00:01:01.000")); } else if(range(i, 9, 11)) { // 指数 testCaseCell.setCellValue(123.456789); } else if(i == 49) { // テキスト testCaseCell.setCellValue("テキスト"); } else if(range(i, 50, 59)) { testCaseCell.setCellValue(Timestamp.valueOf("2000-02-29 10:19:23.123")); } // インデックス indexCell.setCellValue(i); // フォーマット formatCell.setCellValue(BuiltinFormats.getBuiltinFormat(i)); } }
private void changeValueIfNeeded(Cell cell) { //validate String originalValue = cell.getStringCellValue(); if (originalValue == null || originalValue.isEmpty()) return; //interprets Object result = interpreter.parseTemplate(originalValue, context, variables, formatter); //converts if (result != null) { if (formatter.format() != null) { //create data format DataFormat df = workbook.createDataFormat(); short sdf = df.getFormat(formatter.format()); //set format CellStyle style = cell.getCellStyle(); if (style == null) { style = workbook.createCellStyle(); } style.setDataFormat(sdf); } if (result instanceof Date) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue((Date) result); } else if (result instanceof Calendar) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue((Calendar) result); } else if (result instanceof Number) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); Number numValue = (Number) result; cell.setCellValue(numValue.doubleValue()); } else if (result instanceof Boolean) { cell.setCellType(Cell.CELL_TYPE_BOOLEAN); Boolean boolValue = (Boolean) result; cell.setCellValue(boolValue); } else { String strValue = result.toString(); if (!originalValue.equals(strValue)) { cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(strValue); } } } else { cell.setCellValue((String) null); } }
private void createDateFormatStyle() { dateStyle = wb.createCellStyle(); DataFormat df = wb.createDataFormat(); dateStyle.setDataFormat(df.getFormat(DEFAULT_DATE_FORMAT)); }
public CellStyle getCustomDataFormatStyle(String dataFormat) { CellStyle cellStyle = wb.createCellStyle(); DataFormat df = wb.createDataFormat(); cellStyle.setDataFormat(df.getFormat(dataFormat)); return cellStyle; }
/** * Not supported */ @Override public DataFormat createDataFormat() { throw new UnsupportedOperationException(); }
public static short dateFormat(Workbook workbook) { DataFormat format = workbook.createDataFormat(); return format.getFormat("mm/dd/yyyy hh:mm"); }
public static CellStyle createDateStyle(Workbook workbook, String format) { CellStyle style = workbook.createCellStyle(); DataFormat df = workbook.createDataFormat(); style.setDataFormat(df.getFormat(format)); return style; }
/** * Test applying Format and Style from cell (from a template) when writing fields * * @param fileType * @throws Exception */ private void testStyleFormat( String fileType ) throws Exception { setupStepMock( fileType ); createStepMeta( fileType ); createStepData( fileType ); step.init( stepMeta, stepData ); // We do not run transformation or executing the whole step // instead we just execute ExcelWriterStepData.writeNextLine() to write to Excel workbook object // Values are written in A2:D2 and A3:D3 rows List<Object[]> rows = createRowData(); for ( int i = 0; i < rows.size(); i++ ) { step.writeNextLine( rows.get( i ) ); } // Custom styles are loaded from G1 cell Row xlsRow = stepData.sheet.getRow( 0 ); Cell baseCell = xlsRow.getCell( 6 ); CellStyle baseCellStyle = baseCell.getCellStyle(); DataFormat format = stepData.wb.createDataFormat(); // Check style of the exported values in A3:D3 xlsRow = stepData.sheet.getRow( 2 ); for ( int i = 0; i < stepData.inputRowMeta.size(); i++ ) { Cell cell = xlsRow.getCell( i ); CellStyle cellStyle = cell.getCellStyle(); if ( i > 0 ) { assertEquals( cellStyle.getBorderRight(), baseCellStyle.getBorderRight() ); assertEquals( cellStyle.getFillPattern(), baseCellStyle.getFillPattern() ); } else { // cell A2/A3 has no custom style assertFalse( cellStyle.getBorderRight() == baseCellStyle.getBorderRight() ); assertFalse( cellStyle.getFillPattern() == baseCellStyle.getFillPattern() ); } if ( i != 1 ) { assertEquals( format.getFormat( cellStyle.getDataFormat() ), "0.00000" ); } else { // cell B2/B3 use different format from the custom style assertEquals( format.getFormat( cellStyle.getDataFormat() ), "##0,000.0" ); } } }
/** * Setup the data necessary for Excel Writer step * * @param fileType * @throws KettleException */ private void createStepData( String fileType ) throws KettleException { stepData = new ExcelWriterStepData(); stepData.inputRowMeta = step.getInputRowMeta().clone(); stepData.outputRowMeta = step.getInputRowMeta().clone(); // we don't run transformation so ExcelWriterStep.processRow() doesn't get executed // we populate the ExcelWriterStepData with bare minimum required values CellReference cellRef = new CellReference( stepMeta.getStartingCell() ); stepData.startingRow = cellRef.getRow(); stepData.startingCol = cellRef.getCol(); stepData.posX = stepData.startingCol; stepData.posY = stepData.startingRow; int numOfFields = stepData.inputRowMeta.size(); stepData.fieldnrs = new int[numOfFields]; stepData.linkfieldnrs = new int[numOfFields]; stepData.commentfieldnrs = new int[numOfFields]; for ( int i = 0; i < numOfFields; i++ ) { stepData.fieldnrs[i] = i; stepData.linkfieldnrs[i] = -1; stepData.commentfieldnrs[i] = -1; } // we avoid reading/writing Excel files, so ExcelWriterStep.prepareNextOutputFile() doesn't get executed // create Excel workbook object stepData.wb = stepMeta.getExtension().equalsIgnoreCase( "xlsx" ) ? new XSSFWorkbook() : new HSSFWorkbook(); stepData.sheet = stepData.wb.createSheet(); stepData.file = null; stepData.clearStyleCache( numOfFields ); // we avoid reading template file from disk // so set beforehand cells with custom style and formatting DataFormat format = stepData.wb.createDataFormat(); Row xlsRow = stepData.sheet.createRow( 0 ); // Cell F1 has custom style applied, used as template Cell cell = xlsRow.createCell( 5 ); CellStyle cellStyle = stepData.wb.createCellStyle(); cellStyle.setBorderRight( CellStyle.BORDER_THICK ); cellStyle.setFillPattern( CellStyle.FINE_DOTS ); cell.setCellStyle( cellStyle ); // Cell G1 has same style, but also a custom data format cellStyle = stepData.wb.createCellStyle(); cellStyle.cloneStyleFrom( cell.getCellStyle() ); cell = xlsRow.createCell( 6 ); cellStyle.setDataFormat( format.getFormat( "##0,000.0" ) ); cell.setCellStyle( cellStyle ); }