@Override public void createCellStyles(Workbook wb) { if (wb == null) { return; } CreationHelper createHelper = wb.getCreationHelper(); // Headers CellStyle headerStyle = wb.createCellStyle(); headerStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex()); headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); Font font = wb.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); font.setColor(HSSFColor.WHITE.index); headerStyle.setFont(font); cellStyleMap.put(STYLE_HELP_HEADER, headerStyle); cellStyleMap.put(STYLE_RECORD_HEADER, headerStyle); cellStyleMap.put(STYLE_LOCATION_HEADER, headerStyle); cellStyleMap.put(STYLE_TAXONOMY_HEADER, headerStyle); // Date and Time CellStyle dateStyle = wb.createCellStyle(); dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("D MMM YYYY")); cellStyleMap.put(STYLE_DATE_CELL, dateStyle); CellStyle timeStyle = wb.createCellStyle(); timeStyle.setDataFormat(createHelper.createDataFormat().getFormat("HH:MM")); cellStyleMap.put(STYLE_TIME_CELL, timeStyle); }
/* * Don't hardcode US Locale for datetimes in Excel. Experiment a bit. */ public static void issue26() throws InvalidFormatException, IOException { System.out.println("Testing issue26 ================================="); Workbook wb = new XSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("Sheet1"); Row row = sheet.createRow(0); // first cell Cell cell0 = row.createCell(0); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); cell0.setCellValue(new Date(1385903303326L)); // 12/1/2013 08:08 AM cell0.setCellStyle(cellStyle); // second cell using another format with French locale CellStyle cs2 = wb.createCellStyle(); String excelFormatPrefix = DateFormatConverter.getPrefixForLocale(Locale.FRENCH); System.out.println("The LOCALE prefix is: " + excelFormatPrefix); String excelFormatPattern = excelFormatPrefix + "dd MMM, yyyy;@"; System.out.println( "Converted pattern in FRENCH locale is: " + DateFormatConverter.convert(Locale.FRENCH, "m/d/yy h:mm:ss")); DataFormat df = wb.createDataFormat(); cs2.setDataFormat(df.getFormat(excelFormatPattern)); Cell cell1 = row.createCell(1); cell1.setCellValue(new Date(1385903303326L)); cell1.setCellStyle(cs2); FileOutputStream out = new FileOutputStream("/tmp/issue26_out.xlsx"); wb.write(out); out.close(); System.out.println("Wrote /tmp/issue26_out.xlsx"); }
/** Create a library of cell styles */ private static Map<String, CellStyle> createStyles(Workbook wb) { Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); CellStyle style; Font titleFont = wb.createFont(); titleFont.setFontHeightInPoints((short) 18); titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFont(titleFont); styles.put("title", style); Font monthFont = wb.createFont(); monthFont.setFontHeightInPoints((short) 11); monthFont.setColor(IndexedColors.WHITE.getIndex()); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(monthFont); style.setWrapText(true); styles.put("header", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setWrapText(true); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("cell", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setDataFormat(wb.createDataFormat().getFormat("0.00")); styles.put("formula", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setDataFormat(wb.createDataFormat().getFormat("0.00")); styles.put("formula_2", style); return styles; }
// ����Excel public String ExcelExport() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); String ids = request.getParameter("ids"); List<Dise> list = new ArrayList<Dise>(); String[] array = ids.split(","); int[] id = new int[array.length]; for (int i = 0; i < id.length; i++) { Dise dise = DiseService.findById(Integer.valueOf(array[i])); list.add(dise); } Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("ѧ����Ϣ"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("ѧ��"); row.createCell(1).setCellValue("����"); row.createCell(2).setCellValue("����"); row.createCell(3).setCellValue("�Ա�"); row.createCell(4).setCellValue("��ַ"); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); for (int i = 1; i <= list.size(); i++) { Dise stu = list.get(i - 1); row = sheet.createRow(i); row.createCell(0).setCellValue(stu.getIds()); row.createCell(1).setCellValue(stu.getName()); row.createCell(2).setCellValue(stu.getA()); row.createCell(3).setCellValue(stu.getB()); row.createCell(4).setCellValue(stu.getC()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); workbook.write(baos); excelFile = new ByteArrayInputStream(baos.toByteArray()); baos.close(); return "excel"; }
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 Result populateLoansTable(Sheet savingsTransactionSheet) { Result result = new Result(); Workbook workbook = savingsTransactionSheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat("dd/mm/yy"); dateCellStyle.setDataFormat(df); int rowIndex = 1; Row row; Collections.sort(savings, CompactSavingsAccount.ClientNameComparator); try { for (CompactSavingsAccount savingsAccount : savings) { row = savingsTransactionSheet.createRow(rowIndex++); writeString(LOOKUP_CLIENT_NAME_COL, row, savingsAccount.getClientName()); writeLong(LOOKUP_ACCOUNT_NO_COL, row, Long.parseLong(savingsAccount.getAccountNo())); writeString(LOOKUP_PRODUCT_COL, row, savingsAccount.getSavingsProductName()); writeDouble(LOOKUP_OPENING_BALANCE_COL, row, savingsAccount.getMinRequiredOpeningBalance()); writeDate( LOOKUP_SAVINGS_ACTIVATION_DATE_COL, row, savingsAccount.getTimeline().getActivatedOnDate().get(2) + "/" + savingsAccount.getTimeline().getActivatedOnDate().get(1) + "/" + savingsAccount.getTimeline().getActivatedOnDate().get(0), dateCellStyle); } } catch (Exception e) { result.addError(e.getMessage()); logger.error(e.getMessage()); } return result; }
private CellStyle getDateFormatStyle(HSSFCell poiCell) { final HSSFWorkbook poiWorkbook = poiCell.getRow().getSheet().getWorkbook(); CellStyle dateFormatStyle = poiWorkbook.createCellStyle(); CreationHelper createHelper = poiWorkbook.getCreationHelper(); dateFormatStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:MM:ss")); dateFormatStyle.setAlignment(CellStyle.ALIGN_LEFT); return dateFormatStyle; }
@Override public void setDateTimePattern(String dateTimePattern) { this.dateTimePattern = dateTimePattern; DateTimeConverter dtConverter = (DateTimeConverter) converters.lookup(Date.class); dtConverter.setDateTimePattern(dateTimePattern); dateCellStyle = workbook.createCellStyle(); CreationHelper helper = workbook.getCreationHelper(); dateCellStyle.setDataFormat(helper.createDataFormat().getFormat(dateTimePattern)); }
private void makeTemporalCell(Cell retVal, Date cellObj, String format) { CreationHelper creationHelper = workbook.getCreationHelper(); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat(format)); retVal.setCellStyle(cellStyle); if (null != cellObj) { Calendar calendar = Calendar.getInstance(); calendar.setTime((Date) cellObj); retVal.setCellValue(calendar); } }
/** * Creates a new instance. * * @param workbook target workbook * @throws IllegalArgumentException if some parameters were {@code null} */ WorkbookInfo(Workbook workbook) { if (workbook == null) { throw new IllegalArgumentException("workbook must not be null"); // $NON-NLS-1$ } this.workbook = workbook; Font font = workbook.createFont(); commonStyle = workbook.createCellStyle(); commonStyle.setFont(font); commonStyle.setBorderTop(BorderStyle.THIN); commonStyle.setBorderBottom(BorderStyle.THIN); commonStyle.setBorderLeft(BorderStyle.THIN); commonStyle.setBorderRight(BorderStyle.THIN); titleStyle = workbook.createCellStyle(); titleStyle.cloneStyleFrom(commonStyle); titleStyle.setLocked(true); titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); titleStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex()); titleStyle.setAlignment(HorizontalAlignment.CENTER); CreationHelper helper = workbook.getCreationHelper(); DataFormat df = helper.createDataFormat(); dataStyle = workbook.createCellStyle(); dataStyle.cloneStyleFrom(commonStyle); dateDataStyle = workbook.createCellStyle(); dateDataStyle.cloneStyleFrom(commonStyle); dateDataStyle.setDataFormat(df.getFormat("yyyy-mm-dd")); // $NON-NLS-1$ timeDataStyle = workbook.createCellStyle(); timeDataStyle.cloneStyleFrom(commonStyle); timeDataStyle.setDataFormat(df.getFormat("hh:mm:ss")); // $NON-NLS-1$ datetimeDataStyle = workbook.createCellStyle(); datetimeDataStyle.cloneStyleFrom(commonStyle); datetimeDataStyle.setDataFormat(df.getFormat("yyyy-mm-dd hh:mm:ss")); // $NON-NLS-1$ }
public void outputIntAdapter(DataBean dataBean, Object fieldValue, String fieldName, Cell cell) throws AdapterException { log.debug( "in DefaultOutputAdapter:outputIntAdapter fieldName:{} fieldValue:{}", fieldName, fieldValue); if (ObjectHelper.isNullOrEmptyString(fieldValue)) return; Workbook workbook = cell.getSheet().getWorkbook(); CellStyle cellStyle = workbook.createCellStyle(); CreationHelper createHelper = workbook.getCreationHelper(); cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("#")); cell.setCellValue(NumberUtils.format(fieldValue, 0)); cell.setCellStyle(cellStyle); }
public CellStyle getNumberFormat( int j, Map<Integer, CellStyle> decimalFormats, Sheet sheet, CreationHelper createHelper, CellType celltype) { int mapPosition = j; if (celltype.equals(CellType.TOTAL)) { mapPosition = j + 90000; } else if (celltype.equals(CellType.SUBTOTAL)) { mapPosition = j + 80000; } else if (celltype.equals(CellType.CF)) { mapPosition = j + 60000; } if (decimalFormats.get(mapPosition) != null) return decimalFormats.get(mapPosition); if (celltype.equals(CellType.CF)) { j = this.getCalculatedFieldDecimals(); } String decimals = ""; for (int i = 0; i < j; i++) { decimals += "0"; } CellStyle cellStyle = this.buildDataCellStyle(sheet); DataFormat df = createHelper.createDataFormat(); String format = "#,##0"; if (decimals.length() > 0) { format += "." + decimals; } cellStyle.setDataFormat(df.getFormat(format)); if (celltype.equals(CellType.TOTAL)) { cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); } if (celltype.equals(CellType.CF)) { cellStyle.setFillForegroundColor(IndexedColors.DARK_YELLOW.getIndex()); } if (celltype.equals(CellType.SUBTOTAL)) { cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); } decimalFormats.put(mapPosition, cellStyle); return cellStyle; }
/** * 添加一个单元格 * * @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; }
public void outputNumericAdapter( DataBean dataBean, Object fieldValue, String fieldName, Cell cell) throws AdapterException { log.debug( "in DefaultOutputAdapter:outputNumericAdapter fieldName:{} fieldValue:{}", fieldName, fieldValue); if (ObjectHelper.isNullOrEmptyString(fieldValue)) return; OutputNumericConfig config = dataBean.getOutputConfig(fieldName); Workbook workbook = cell.getSheet().getWorkbook(); CellStyle cellStyle = workbook.createCellStyle(); CreationHelper createHelper = workbook.getCreationHelper(); StringBuilder format = new StringBuilder("0"); for (int i = 0; i < config.floatCount(); i++) { if (i == 0) format.append("."); format.append("0"); } cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(format.toString())); cell.setCellValue(NumberUtils.format(fieldValue, config.floatCount())); cell.setCellStyle(cellStyle); }
/** * 导出时间适配器 * * @param fieldValue * @param fieldName * @return * @throws AdapterException */ public void outputDateAdapter(DataBean dataBean, Object fieldValue, String fieldName, Cell cell) throws AdapterException { log.debug( "in DefaultOutputAdapter:outputDateAdapter fieldName:{} fieldValue:{}", fieldName, fieldValue); Date date = null; if (fieldValue == null) { log.debug("fieldValue is null return"); cell.setCellValue(""); return; } else if (fieldValue instanceof Date) { log.debug("fieldValue instanceof Date "); date = (Date) fieldValue; } else if (fieldValue instanceof String) { log.debug("fieldValue instanceof String "); InputDateConfig config = dataBean.getInputConfig(fieldName); try { date = DateUtil.formatToDate((String) fieldValue, config.format()); } catch (ParseException e) { throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell); } } else if (fieldValue instanceof Long) { log.debug("fieldValue instanceof Long "); date = new Date((Long) fieldValue); } else { throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell); } Workbook workbook = cell.getSheet().getWorkbook(); OutputDateConfig outputConfig = dataBean.getOutputConfig(fieldName); CellStyle cellStyle = cell.getCellStyle(); if (cellStyle == null) cellStyle = workbook.createCellStyle(); CreationHelper createHelper = workbook.getCreationHelper(); cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(outputConfig.format())); cell.setCellStyle(cellStyle); cell.setCellValue(date); }
public void setCellMoney(int numRow, int numCol) { try { if (wb.getSheetAt(0) != null) { Sheet aSheet = wb.getSheetAt(0); DataFormat format = wb.createDataFormat(); Row row = aSheet.getRow((short) numRow); Cell csCell = row.getCell((short) numCol); CellStyle style = wb.createCellStyle(); style.setDataFormat(format.getFormat("0.00")); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBottomBorderColor(HSSFColor.BLACK.index); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setLeftBorderColor(HSSFColor.BLACK.index); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setRightBorderColor(HSSFColor.BLACK.index); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setTopBorderColor(HSSFColor.BLACK.index); csCell.setCellStyle(style); } } catch (Exception e) { System.out.println("insertDataToExcel" + e); } }
/* * (non-Javadoc) * * @see * com.toolsverse.etl.connector.DataSetConnector#prePersist(com.toolsverse * .etl.connector.DataSetConnectorParams, com.toolsverse.etl.common.DataSet, * com.toolsverse.etl.driver.Driver) */ @SuppressWarnings("resource") public void prePersist(ExcelConnectorParams params, DataSet dataSet, Driver driver) throws Exception { String fileName = null; OutputStream out = null; if (params.getOutputStream() == null) { fileName = SystemConfig.instance() .getPathUsingAppFolders( params.getFileName( dataSet.getOwnerName() != null ? dataSet.getOwnerName() : dataSet.getName(), ".xls", true)); params.setRealFileName(fileName); out = new FileOutputStream(fileName); if (params.getTransactionMonitor() != null) params.getTransactionMonitor().addFile(fileName); } else out = params.getOutputStream(); params.setOut(out); Workbook workbook = new HSSFWorkbook(); params.setWorkbook(workbook); Sheet sheet = workbook.createSheet( Utils.isNothing(params.getSheetName()) ? dataSet.getName() : params.getSheetName()); params.setSheet(sheet); Font labelFont = workbook.createFont(); labelFont.setBoldweight(Font.BOLDWEIGHT_BOLD); CellStyle labelCellStyle = workbook.createCellStyle(); labelCellStyle.setFont(labelFont); DataFormat dateTimeFormat = workbook.createDataFormat(); CellStyle dateTimeCellStyle = workbook.createCellStyle(); dateTimeCellStyle.setDataFormat(dateTimeFormat.getFormat(params.getDateTimeFormat())); params.setDateTimeCellStyle(dateTimeCellStyle); DataFormat dateFormat = workbook.createDataFormat(); CellStyle dateCellStyle = workbook.createCellStyle(); dateCellStyle.setDataFormat(dateFormat.getFormat(params.getDateFormat())); params.setDateCellStyle(dateCellStyle); DataFormat timeFormat = workbook.createDataFormat(); CellStyle timeCellStyle = workbook.createCellStyle(); timeCellStyle.setDataFormat(timeFormat.getFormat(params.getTimeFormat())); params.setTimeCellStyle(timeCellStyle); // column names Row excelRow = sheet.createRow(0); // metadata int col = 0; for (FieldDef fieldDef : dataSet.getFields().getList()) { if (!fieldDef.isVisible()) continue; Cell labelCell = excelRow.createCell(col++, Cell.CELL_TYPE_STRING); labelCell.setCellStyle(labelCellStyle); labelCell.setCellValue(fieldDef.getName()); } params.setPrePersistOccured(true); }
private static Map createStyles(Workbook wb) { Map styles = new HashMap(); Font titleFont = wb.createFont(); titleFont.setFontHeightInPoints((short) 14); titleFont.setFontName("Trebuchet MS"); CellStyle style = wb.createCellStyle(); style.setFont(titleFont); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); styles.put("title", style); Font itemFont = wb.createFont(); itemFont.setFontHeightInPoints((short) 9); itemFont.setFontName("Trebuchet MS"); style = wb.createCellStyle(); style.setAlignment((short) 1); style.setFont(itemFont); styles.put("item_left", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); styles.put("item_right", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat( wb.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)")); styles.put("input_$", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat(wb.createDataFormat().getFormat("0.000%")); styles.put("input_%", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat(wb.createDataFormat().getFormat("0")); styles.put("input_i", style); style = wb.createCellStyle(); style.setAlignment((short) 2); style.setFont(itemFont); style.setDataFormat(wb.createDataFormat().getFormat("m/d/yy")); styles.put("input_d", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat(wb.createDataFormat().getFormat("$##,##0.00")); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern((short) 1); styles.put("formula_$", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat(wb.createDataFormat().getFormat("0")); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern((short) 1); styles.put("formula_i", style); return styles; }
private static Map<String, CellStyle> createStyles(Workbook wb) { Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); short borderColor = IndexedColors.GREY_50_PERCENT.getIndex(); CellStyle style; DataFormat format = wb.createDataFormat(); Font titleFont = wb.createFont(); titleFont.setFontName("Tahoma"); titleFont.setFontHeightInPoints((short) 12); titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFont(titleFont); styles.put("title", style); Font headFont = wb.createFont(); headFont.setFontName("Tahoma"); headFont.setFontHeightInPoints((short) 11); headFont.setColor(IndexedColors.WHITE.getIndex()); headFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(headFont); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setWrapText(true); styles.put("header", style); Font groupFont = wb.createFont(); groupFont.setFontName("Tahoma"); groupFont.setFontHeightInPoints((short) 11); groupFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setWrapText(true); style.setFont(groupFont); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("groupleft", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setWrapText(true); style.setFont(groupFont); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("groupright", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setWrapText(true); /* style.setFont(groupFont); */ style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("groupcenter", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setWrapText(true); style.setDataFormat(format.getFormat("#,##0")); /* style.setFont(groupFont); */ style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("groupnumber", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setWrapText(true); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); /* style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); */ styles.put("cellleft", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setWrapText(true); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("cellcenter", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setWrapText(true); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("cellright", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setWrapText(true); style.setDataFormat(format.getFormat("#,##0")); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("cellnumber", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setWrapText(true); style.setDataFormat(format.getFormat("#,##0.00")); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("cellnumber2", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_TOP); style.setWrapText(true); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); styles.put("celltop", style); return styles; }
public static void writeExcelFile(String fileLocation) { try { FileOutputStream fileOut = new FileOutputStream(fileLocation); HSSFWorkbook workbook = new HSSFWorkbook(); Font bold = workbook.createFont(); // Create font bold.setBoldweight(Font.BOLDWEIGHT_BOLD); // Make font bold CellStyle correctCell = workbook.createCellStyle(); correctCell.setFillForegroundColor(HSSFColor.GREEN.index); correctCell.setFillBackgroundColor(HSSFColor.GREEN.index); correctCell.setFillPattern(CellStyle.SOLID_FOREGROUND); CellStyle incorrectCell = workbook.createCellStyle(); incorrectCell.setFillForegroundColor(HSSFColor.RED.index); incorrectCell.setFillBackgroundColor(HSSFColor.RED.index); incorrectCell.setFillPattern(CellStyle.SOLID_FOREGROUND); CellStyle classificationCells = workbook.createCellStyle(); classificationCells.setFillForegroundColor(HSSFColor.YELLOW.index); classificationCells.setFillBackgroundColor(HSSFColor.YELLOW.index); classificationCells.setFillPattern(CellStyle.SOLID_FOREGROUND); CellStyle attributeNameCells = workbook.createCellStyle(); attributeNameCells.setFont(bold); CellStyle classificationAttributeCell = workbook.createCellStyle(); classificationAttributeCell.setFillForegroundColor(HSSFColor.YELLOW.index); classificationAttributeCell.setFillBackgroundColor(HSSFColor.YELLOW.index); classificationAttributeCell.setFillPattern(CellStyle.SOLID_FOREGROUND); classificationAttributeCell.setFont(bold); Sheet worksheet = workbook.createSheet("Results"); Row currRow = worksheet.createRow(0); for (int attribute = 0; attribute < metadataLL.size() + 1; attribute++) { Cell currCell = currRow.createCell(attribute); if (attribute < metadataLL.size()) { currCell.setCellValue(metadataLL.get(attribute)[0]); if (metadataLL.get(attribute)[2].compareTo("classifier") == 0) { currCell.setCellStyle(classificationAttributeCell); } else { currCell.setCellStyle(attributeNameCells); } } else { currCell.setCellValue("Guessed Classification"); currCell.setCellStyle(attributeNameCells); } } int correct = 0; int incorrect = 0; for (int node = 0; node < testDataLL.size(); node++) { currRow = worksheet.createRow(node + 1); // Offset by one since first row is header data int classifierCompleted = 0; // Necessary for if data does not end in classifier for (int attribute = 0; attribute < metadataLL.size() + 2; attribute++) // +1 for the row for guessed data +1 for the row that contains { Cell currCell = currRow.createCell(attribute); if (attribute < metadataLL.size()) // Print testingData { if (metadataLL.get(attribute)[2].compareTo("classifier") == 0) { currCell.setCellValue(actualClassifications.get(node)); currCell.setCellStyle(classificationCells); classifierCompleted++; } else { currCell.setCellValue(testDataLL.get(node)[attribute - classifierCompleted]); } } else if (attribute == metadataLL.size()) // Print guessed classification { currCell.setCellValue(guessedClassifications.get(node)); if (guessedClassifications.get(node).compareTo(actualClassifications.get(node)) == 0) { currCell.setCellStyle(correctCell); correct++; } else { currCell.setCellStyle(incorrectCell); incorrect++; } if (node == testDataLL.size() - 1) // If this is the last loop { double precentRight = (double) correct / (correct + incorrect); currRow = worksheet.createRow(node + 2); currCell = currRow.createCell(attribute); currCell.setCellValue(precentRight); if (precentRight > .90) { correctCell.setDataFormat(workbook.createDataFormat().getFormat("0.000%")); currCell.setCellStyle(correctCell); } else { incorrectCell.setDataFormat(workbook.createDataFormat().getFormat("0.000%")); currCell.setCellStyle(incorrectCell); } } } else if (attribute == metadataLL.size() + 1) // Print potential bad training data if the flag is true { if (unseenDataFlag.get(node)) { currCell.setCellValue( "This node an attribute value not in the training set, classifier selected is based on most frequent classifier. If laplacian smoothing is 1 or more this likely wont happen"); // TODO make this a bit shorter } } } } worksheet = workbook.createSheet("Training Data"); currRow = worksheet.createRow(0); for (int attribute = 0; attribute < metadataLL.size(); attribute++) { Cell currCell = currRow.createCell(attribute); currCell.setCellValue(metadataLL.get(attribute)[0]); currCell.setCellStyle(attributeNameCells); } for (int node = 0; node < trainingDataLL.size(); node++) { currRow = worksheet.createRow(node + 1); // Offset by one since first row is header data int classifierCompleted = 0; // Necessary for if data does not end in classifier for (int attribute = 0; attribute < metadataLL.size(); attribute++) { Cell currCell = currRow.createCell(attribute); if (metadataLL.get(attribute)[2].compareTo("classifier") == 0) { currCell.setCellValue(knownClassifications.get(node)); classifierCompleted++; } else { currCell.setCellValue(trainingDataLL.get(node)[attribute - classifierCompleted]); } } } worksheet = workbook.createSheet("Likelihood"); currRow = worksheet.createRow(0); int largestAttributeSize = 0; for (int attribute = 0; attribute < classifier.size(); attribute++) { if (classifier.get(attribute).size() > largestAttributeSize) { largestAttributeSize = classifier.get(attribute).size(); } } // Label attributes along the top for (int i = 0; i < metadataLL.size(); i++) { if (i == 0) { Cell currCell = currRow.createCell(i); // currCell.setCellValue("Attributes"); currCell.setCellStyle(attributeNameCells); } else { Cell currCell = currRow.createCell(i); currCell.setCellValue( metadataLL .get(i - 1)[0]); // -1 since the first cell does not contain a attribute name currCell.setCellStyle(attributeNameCells); } } // List possible classifications on the side and classification likelihoods at the end for (int i = 0; i < (largestAttributeSize * (classificationTypes.size() + 1) + classificationTypes.size() + 1); i++) // +1 since the first row of each stride lists each attributes string of what // occurrence the likelihoods are displaying { // +classificationTypes.size() so we can list the classification types likelihood at the end currRow = worksheet.createRow(i + 1); // +1 since first row is attribute names Cell currCell = currRow.createCell(0); int currentClassificationType = i % (classificationTypes.size() + 1); // +1 since the first row of each stride lists each attributes string of // what occurrence the likelihoods are displaying // List the classification type of each row along the side if (i < largestAttributeSize * (classificationTypes.size() + 1)) // +1 since the first row of each stride lists each attributes string of // what occurrence the likelihoods are displaying { for (int j = 0; j < classificationTypes.size() + 1; j++) // +1 since the first row of each stride lists each attributes string of what // occurrence the likelihoods are displaying { if (currentClassificationType == 0) { // Do nothing for now may have it say something later } else if (currentClassificationType == j) { currCell.setCellValue( classificationTypes.get( j - 1)); // -1 since the first cell does not contain a classification type } } } else // List the likelihood of each classification at the end { for (int j = 0; j < classificationTypes.size() + 1; j++) // +1 since the first row of each stride lists each attributes string of what // occurrence the likelihoods are displaying { if (currentClassificationType == 0) { // Do nothing for now may have it say value later } else if (currentClassificationType == j) { currCell.setCellValue( "Likelihood of: " + classificationTypes.get(j - 1) + " is " + classificationLikelihood.get( j - 1)); // -1 since the first cell does not contain a classification type } } } currCell.setCellStyle(attributeNameCells); } // List the data for (int attribute = 0; attribute < classifier.size(); attribute++) { for (int occurrences = 0; occurrences < classifier.get(attribute).size(); occurrences++) { for (int classification = 0; classification < classifier.get(attribute).get(occurrences).length; classification++) { currRow = worksheet.getRow( (occurrences * classifier.get(attribute).get(occurrences).length + classification) + 1); // +1 since first row is attribute names Cell currCell = currRow.createCell( (attribute) + 1); // TODO figure out why this errors out at i:0 j:4 k:0 // largestAttributeSize:105 on kidney dataset currCell.setCellValue(classifier.get(attribute).get(occurrences)[classification]); } } } workbook.write(fileOut); workbook.close(); workbook.close(); } catch (FileNotFoundException e) { System.out.println("Error file not found"); e.printStackTrace(); System.exit(0); } catch (IOException e) { System.out.println("Unable to output file, is the output destination writelocked?"); e.printStackTrace(); System.exit(0); } }
public void process2HTTP( ExportModel expModel, UISimpleViewExport uis, HttpServletResponse hsr, DateTimeHelper dth) { try { String strFileName = uis.getDownloadFileName(); Workbook wbCurrent = null; if (strFileName.toLowerCase().endsWith(".xlsx")) { wbCurrent = new XSSFWorkbook(); } else { wbCurrent = new HSSFWorkbook(); } HashMap<String, CellStyle> hsCS = new HashMap<String, CellStyle>(); CreationHelper cr = wbCurrent.getCreationHelper(); CellStyle csDate = wbCurrent.createCellStyle(); csDate.setDataFormat(cr.createDataFormat().getFormat(dth.getDFDate().toPattern())); CellStyle csDateTime = wbCurrent.createCellStyle(); csDateTime.setDataFormat(cr.createDataFormat().getFormat(dth.getDFDateTime().toPattern())); CellStyle csTime = wbCurrent.createCellStyle(); csTime.setDataFormat(cr.createDataFormat().getFormat(dth.getDFTime().toPattern())); hsCS.put("DATE", csDate); hsCS.put("TIME", csTime); hsCS.put("DATETIME", csDateTime); Sheet sh = wbCurrent.createSheet("SVE Export"); int nRowCount = 0; // BUILDING HEADER if (uis.isIncludeHeader()) { Row rw = sh.createRow(nRowCount); int nCol = 0; for (ExportColumn expColumn : expModel.getColumns()) { rw.createCell(nCol).setCellValue(expColumn.getColumnName()); nCol++; } nRowCount++; } // Processing Values for (ExportDataRow expRow : expModel.getRows()) { Row rw = sh.createRow(nRowCount); int nCol = 0; for (ExportColumn expColumn : expModel.getColumns()) { Cell clCurrent = rw.createCell(nCol); setCellValue(expRow.getValue(expColumn.getPosition()), clCurrent, expColumn, hsCS); nCol++; } nRowCount++; } for (int nCol = 0; nCol < expModel.getColumns().size(); nCol++) { sh.autoSizeColumn(nCol); } if (strFileName.toLowerCase().endsWith(".xlsx")) { hsr.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); } else if (strFileName.toLowerCase().endsWith("xls")) { hsr.setContentType("application/vnd.ms-excel"); } else { hsr.setContentType("application/octet-stream"); } hsr.addHeader("Content-disposition", "inline; filename=\"" + strFileName + "\""); OutputStream os = hsr.getOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); wbCurrent.write(bos); bos.writeTo(os); os.close(); } catch (Exception e) { ErrorPageBuilder.getInstance() .processError(hsr, "Error during SVE-Generation (Workbook Export)", e); } }