Example usage for org.apache.poi.ss.usermodel Cell setCellStyle

List of usage examples for org.apache.poi.ss.usermodel Cell setCellStyle

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Cell setCellStyle.

Prototype

void setCellStyle(CellStyle style);

Source Link

Document

Set the style for the cell.

Usage

From source file:com.gtwm.pb.servlets.ReportDownloader.java

License:Open Source License

/**
 * Return the session report as an Excel file
 * /*  w w w  .j  a  v  a 2 s .co  m*/
 * @param sessionData
 * @return
 */
private ByteArrayOutputStream getSessionReportAsExcel(CompanyInfo company, AppUserInfo user,
        SessionDataInfo sessionData) throws AgileBaseException, IOException, SQLException {
    BaseReportInfo report = sessionData.getReport();
    if (report == null) {
        throw new ObjectNotFoundException("No report found in the session");
    }
    // create Excel spreadsheet
    Workbook workbook = new SXSSFWorkbook();
    // the pane 2 report
    String reportName = report.getReportName();
    // Replace any invalid characters : \ / ? * [ or ]
    // http://support.microsoft.com/kb/215205
    reportName = reportName.replaceAll("[\\/\\:\\\\\\?\\*\\[\\]]", "-");
    Sheet reportSheet;
    try {
        reportSheet = workbook.createSheet(reportName);
    } catch (IllegalArgumentException iaex) {
        reportSheet = workbook.createSheet(reportName + " " + report.getInternalReportName());
    }
    int rowNum = 0;
    // header
    CellStyle boldCellStyle = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    boldCellStyle.setFont(font);
    Row row = reportSheet.createRow(rowNum);
    int columnNum = 0;
    Set<ReportFieldInfo> reportFields = report.getReportFields();
    for (ReportFieldInfo reportField : reportFields) {
        Cell cell = row.createCell(columnNum);
        cell.setCellValue(reportField.getFieldName());
        cell.setCellStyle(boldCellStyle);
        BaseField field = reportField.getBaseField();
        if (field.equals(field.getTableContainingField().getPrimaryKey())) {
            reportSheet.setColumnHidden(columnNum, true);
        }
        columnNum++;
    }
    // data
    rowNum++;
    DataManagementInfo dataManagement = this.databaseDefn.getDataManagement();
    List<DataRowInfo> reportDataRows = dataManagement.getReportDataRows(company, report,
            sessionData.getReportFilterValues(), false, sessionData.getReportSorts(), -1, QuickFilterType.AND,
            false);
    String fieldValue = "";
    boolean defaultReport = (report.equals(report.getParentTable().getDefaultReport()));
    for (DataRowInfo dataRow : reportDataRows) {
        Map<BaseField, DataRowFieldInfo> dataRowFieldMap = dataRow.getDataRowFields();
        row = reportSheet.createRow(rowNum);
        columnNum = 0;
        for (ReportFieldInfo reportField : reportFields) {
            BaseField field = reportField.getBaseField();
            if (field instanceof TextField) {
                fieldValue = dataRowFieldMap.get(field).getKeyValue();
            } else {
                fieldValue = dataRowFieldMap.get(field).getDisplayValue();
            }
            if (!fieldValue.equals("")) {
                Cell cell;
                DatabaseFieldType dbFieldType = field.getDbType();
                if ((defaultReport) && (field instanceof RelationField)) {
                    dbFieldType = ((RelationField) field).getDisplayField().getDbType();
                }
                switch (dbFieldType) {
                case FLOAT:
                    cell = row.createCell(columnNum, Cell.CELL_TYPE_NUMERIC);
                    try {
                        cell.setCellValue(Double.valueOf(fieldValue.replace(",", "")));
                    } catch (NumberFormatException nfex) {
                        // Fall back to a string representation
                        cell = row.createCell(columnNum, Cell.CELL_TYPE_STRING);
                        cell.setCellValue(fieldValue);
                    }
                    break;
                case INTEGER:
                case SERIAL:
                    cell = row.createCell(columnNum, Cell.CELL_TYPE_NUMERIC);
                    try {
                        cell.setCellValue(Integer.valueOf(fieldValue.replace(",", "")));
                    } catch (NumberFormatException nfex) {
                        logger.debug(nfex.toString() + ": value " + fieldValue.replace(",", ""));
                        // Fall back to a string representation
                        cell = row.createCell(columnNum, Cell.CELL_TYPE_STRING);
                        cell.setCellValue(fieldValue);
                        logger.debug("Successfully set string instead");
                    }
                    break;
                case VARCHAR:
                default:
                    cell = row.createCell(columnNum, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(Helpers.unencodeHtml(fieldValue));
                    break;
                }
            }
            columnNum++;
        }
        rowNum++;
    }
    // Export info worksheet
    addReportMetaDataWorksheet(company, user, sessionData, report, workbook);
    // one worksheet for each of the report summaries
    for (ChartInfo savedChart : report.getSavedCharts()) {
        this.addSummaryWorksheet(company, sessionData, savedChart, workbook);
    }
    // the default summary
    ChartInfo reportSummary = report.getChart();
    Set<ChartAggregateInfo> aggregateFunctions = reportSummary.getAggregateFunctions();
    Set<ChartGroupingInfo> groupings = reportSummary.getGroupings();
    if ((groupings.size() > 0) || (aggregateFunctions.size() > 0)) {
        this.addSummaryWorksheet(company, sessionData, reportSummary, workbook);
    }
    // write to output
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    workbook.write(outputStream);
    return outputStream;
}

From source file:com.gtwm.pb.servlets.ReportDownloader.java

License:Open Source License

/**
 * Add a worksheet to the report for the specified workbook
 *///from ww w  . j  a  v  a  2  s .  c  o m
private void addSummaryWorksheet(CompanyInfo company, SessionDataInfo sessionData, ChartInfo reportSummary,
        Workbook workbook) throws SQLException, CantDoThatException {
    ChartDataInfo reportSummaryData = this.databaseDefn.getDataManagement().getChartData(company, reportSummary,
            sessionData.getReportFilterValues(), false);
    if (reportSummaryData == null) {
        return;
    }
    int rowNum;
    Row row;
    Cell cell;
    int columnNum;
    String fieldValue;
    Sheet summarySheet;
    String summaryTitle = reportSummary.getTitle();
    if (summaryTitle == null) {
        summaryTitle = "Summary";
    } else if (summaryTitle.equals("")) {
        summaryTitle = "Summary";
    }
    // Replace any invalid characters : \ / ? * [ or ]
    // http://support.microsoft.com/kb/215205
    summaryTitle = summaryTitle.replaceAll("[\\/\\:\\\\\\?\\*\\[\\]]", "-");
    try {
        summarySheet = workbook.createSheet(summaryTitle);
    } catch (IllegalArgumentException iaex) {
        // sheet name must be unique
        summarySheet = workbook.createSheet(summaryTitle + " " + reportSummary.getId());
    }
    // header
    rowNum = 0;
    row = summarySheet.createRow(rowNum);
    columnNum = 0;
    CellStyle boldCellStyle = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    boldCellStyle.setFont(font);
    Set<ChartAggregateInfo> aggregateFunctions = reportSummary.getAggregateFunctions();
    Set<ChartGroupingInfo> groupings = reportSummary.getGroupings();
    for (ChartGroupingInfo grouping : groupings) {
        BaseField groupingBaseField = grouping.getGroupingReportField().getBaseField();
        if (groupingBaseField instanceof RelationField) {
            fieldValue = groupingBaseField.getTableContainingField() + ": "
                    + ((RelationField) groupingBaseField).getDisplayField();
        } else {
            fieldValue = groupingBaseField.getFieldName();
        }
        cell = row.createCell(columnNum);
        cell.setCellValue(fieldValue);
        cell.setCellStyle(boldCellStyle);
        columnNum++;
    }
    for (ChartAggregateInfo aggregateFunction : aggregateFunctions) {
        fieldValue = aggregateFunction.toString();
        cell = row.createCell(columnNum);
        cell.setCellValue(fieldValue);
        cell.setCellStyle(boldCellStyle);
        columnNum++;
    }
    List<ChartDataRowInfo> reportSummaryDataRows = reportSummaryData.getChartDataRows();
    rowNum++;
    for (ChartDataRowInfo summaryDataRow : reportSummaryDataRows) {
        row = summarySheet.createRow(rowNum);
        columnNum = 0;
        for (ChartGroupingInfo grouping : groupings) {
            fieldValue = summaryDataRow.getGroupingValue(grouping);
            row.createCell(columnNum).setCellValue(fieldValue);
            columnNum++;
        }
        for (ChartAggregateInfo aggregateFunction : aggregateFunctions) {
            Double number = summaryDataRow.getAggregateValue(aggregateFunction).doubleValue();
            row.createCell(columnNum, Cell.CELL_TYPE_NUMERIC).setCellValue(number);
            columnNum++;
        }
        rowNum++;
    }
}

From source file:com.guardias.excel.CalendarToExcel.java

License:Apache License

public static void GenerateExcel(String RutaFile, Calendar calendar, String JSONContenidos,
        Medico AdministratorUser) throws IOException {

    Guardias[] lGuardias;//from   w  w  w.ja v a  2  s  . com

    Gson gson = new GsonBuilder().create();

    lGuardias = gson.fromJson(JSONContenidos, Guardias[].class);

    boolean xlsx = true;
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);

    DateFormat _format = new SimpleDateFormat("yyyy-MM-dd");

    Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, 1);

    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    //create a sheet for each month
    Sheet sheet = wb.createSheet(_format.format(calendar.getTime()));

    CellStyle styleBORDER = wb.createCellStyle();
    styleBORDER.setBorderRight(CellStyle.BORDER_THICK);
    styleBORDER.setBorderBottom(CellStyle.BORDER_THICK);
    styleBORDER.setBorderTop(CellStyle.BORDER_THICK);
    styleBORDER.setBorderLeft(CellStyle.BORDER_THICK);
    styleBORDER.setRightBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
    styleBORDER.setLeftBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
    styleBORDER.setTopBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
    styleBORDER.setBottomBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
    //

    //turn off gridlines
    sheet.setDisplayGridlines(true);
    sheet.autoSizeColumn(0);
    sheet.setPrintGridlines(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    //header with month titles
    Row monthRow = sheet.createRow(1);
    Font fontH = wb.createFont();
    CellStyle CStyleH = wb.createCellStyle();
    CStyleH.setBorderRight(CellStyle.BORDER_THICK);
    CStyleH.setRightBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
    fontH.setBold(true);
    CStyleH.setFont(fontH);
    for (int i = 0; i < days.length; i++) {

        Cell monthCell = monthRow.createCell(i);

        monthCell.setCellStyle(CStyleH);
        monthCell.setCellValue(days[i]);
        sheet.autoSizeColumn(i);

    }

    int cnt = 1, day = 1;
    int rownum = 2;
    for (int j = 0; j < 6; j++) {
        Row row = sheet.createRow(rownum++);
        Row rowGuardias;
        boolean bRowsCreated = false;

        // row.setHeightInPoints(100);
        for (int i = 0; i < days.length; i++) {
            Cell dayCell_1 = row.createCell(i);
            //  Cell dayCell_2 = row.createCell(i*2 + 1);

            int currentDayOfWeek = (calendar.get(Calendar.DAY_OF_WEEK) + 7 - calendar.getFirstDayOfWeek()) % 7;
            //int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);  
            if (cnt > currentDayOfWeek && calendar.get(Calendar.MONTH) == month) {

                Font font = wb.createFont();
                CellStyle CStyle = wb.createCellStyle();
                short colorI = HSSFColor.AQUA.index; // presencia
                //font.set(colorI);
                CStyle.setFillForegroundColor(colorI);
                CStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                //CStyle.setBorderBottom( colorBorder);
                CStyle.setBorderRight(CellStyle.BORDER_THICK);
                CStyle.setBorderBottom(CellStyle.BORDER_THICK);
                CStyle.setBorderTop(CellStyle.BORDER_THICK);
                CStyle.setBorderLeft(CellStyle.BORDER_THICK);
                CStyle.setRightBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
                CStyle.setLeftBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
                CStyle.setTopBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
                CStyle.setBottomBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());
                //CStyle.setFont(font);

                dayCell_1.setCellValue(day);
                dayCell_1.setCellStyle(CStyle);

                sheet.autoSizeColumn(i);

                String _Dia = _format.format(calendar.getTime());

                int DataRowCont = 1; // esto sirve para coger la fila de los datos de cada dia
                for (int d = 0; d < lGuardias.length; d++) {

                    Guardias oGuardias = lGuardias[d];
                    if (oGuardias.getDiaGuardia().equals(_Dia)) {

                        if (!bRowsCreated)
                            rowGuardias = sheet.createRow(rownum++);
                        else
                            rowGuardias = sheet.getRow(row.getRowNum() + DataRowCont);

                        Cell dayCell_1_GUARDIAS = rowGuardias.createCell(i);
                        //    Cell dayCell_2_GUARDIAS = rowGuardias.createCell(i*2 + 1);

                        List<Medico> _lMedico = MedicoDBImpl.getMedicos(oGuardias.getIdMedico(),
                                AdministratorUser.getServicioId());

                        Medico _oMedico = _lMedico.get(0);

                        font = wb.createFont();
                        CStyle = wb.createCellStyle();
                        // PRESENCIA 
                        // LOCALIZADA
                        //XSSFRichTextString richString = new HSSFRichTextString(_oMedico.getApellidos() + " " + _oMedico.getNombre());
                        colorI = HSSFColor.LIGHT_ORANGE.index; // presencia                        
                        if (oGuardias.getTipo().equals(Util.eTipoGuardia.LOCALIZADA.toString().toLowerCase()))
                            colorI = HSSFColor.GREEN.index;
                        else if (oGuardias.getTipo()
                                .equals(Util.eTipoGuardia.REFUERZO.toString().toLowerCase()))
                            colorI = HSSFColor.BLUE.index;
                        else if (oGuardias.getTipo().equals("")) // residente
                            colorI = HSSFColor.RED.index;

                        font.setColor(colorI);

                        CStyle.setFont(font);
                        //CStyle.setBorderBottom( colorBorder);
                        CStyle.setBorderRight(CellStyle.BORDER_THICK);
                        CStyle.setRightBorderColor(IndexedColors.LIGHT_ORANGE.getIndex());

                        dayCell_1_GUARDIAS.setCellValue(_oMedico.getApellidos() + " " + _oMedico.getNombre()
                                + "[" + _oMedico.getIDMEDICO() + "]");
                        dayCell_1_GUARDIAS.setCellStyle(CStyle);

                        DataRowCont++;

                    }

                }
                bRowsCreated = true;

                //      dayCell_1_GUARDIAS.setCellValue(TextoGuardias.toString());

                calendar.set(Calendar.DAY_OF_MONTH, ++day);

                /*if(i == 0 || i == days.length-1) {
                    dayCell_1.setCellStyle(styles.get("weekend_left"));
                    dayCell_2.setCellStyle(styles.get("weekend_right"));
                } else {
                    dayCell_1.setCellStyle(styles.get("workday_left"));
                    dayCell_2.setCellStyle(styles.get("workday_right"));
                }
                } else {
                dayCell_1.setCellStyle(styles.get("grey_left"));
                dayCell_2.setCellStyle(styles.get("grey_right"));*/
            }
            cnt++;
        }
        if (calendar.get(Calendar.MONTH) > month)
            break;
    }
    //  }

    // Write the output to a file
    String file = RutaFile;
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();

    wb.close();

}

From source file:com.hauldata.dbpa.file.book.XlsxTargetSheet.java

License:Apache License

private void setCellValue(Cell cell, Object object) {

    if (object == null) {
        // Leave cell empty
    } else if (object instanceof Short || object instanceof Integer) {
        cell.setCellValue(((Number) object).doubleValue());
        cell.setCellStyle(getOwner().getCellStyle(XlsxCellStyle.INTEGER));
    } else if (object instanceof Long || object instanceof BigInteger) {
        cell.setCellValue(object.toString());
    } else if (object instanceof BigDecimal) {
        cell.setCellValue(((Number) object).doubleValue());

        XlsxCellStyle style;/*from w  ww .  j av  a 2 s  .c  o  m*/
        switch (((BigDecimal) object).scale()) {
        case 2:
            style = XlsxCellStyle.TWO_DECIMAL;
            break;
        case 4:
            style = XlsxCellStyle.FOUR_DECIMAL;
            break;
        default:
            style = XlsxCellStyle.OTHER_DECIMAL;
            break;
        }
        cell.setCellStyle(getOwner().getCellStyle(style));
    } else if (object instanceof Number) {
        cell.setCellValue(((Number) object).doubleValue());
    } else if (object instanceof String) {

        String string = (String) object;
        if (0 < string.length()) {
            ValueXlsxCellStyle valueStyle = ValueXlsxCellStyle.parse(string);
            if (valueStyle.value instanceof Number) {
                cell.setCellValue(((Number) valueStyle.value).doubleValue());
            } else {
                cell.setCellValue((String) valueStyle.value);
            }
            if (valueStyle.style != null) {
                cell.setCellStyle(getOwner().getCellStyle(valueStyle.style));
            }
        } else {
            cell.setCellValue(string);
        }
    } else if (object instanceof Boolean) {
        cell.setCellValue((Boolean) object);
    } else if (object instanceof Date || object instanceof LocalDateTime) {

        Date date;
        LocalTime time;

        if (object instanceof Date) {
            date = (Date) object;
            Instant instant = Instant.ofEpochMilli(date.getTime());
            time = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalTime();
        } else {
            LocalDateTime dateTime = (LocalDateTime) object;
            date = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
            time = dateTime.toLocalTime();
        }

        cell.setCellValue(date);

        CellStyle style = null;
        if (time.equals(LocalTime.MIDNIGHT)) {
            style = getOwner().getCellStyle(XlsxCellStyle.DATE);
        } else {
            style = getOwner().getCellStyle(XlsxCellStyle.DATETIME);
        }
        cell.setCellStyle(style);
    } else {
        cell.setCellValue(object.toString());
    }
}

From source file:com.hauldata.dbpa.file.book.XlsxTargetSheet.java

License:Apache License

private Styles setCellStyle(Cell cell, Styles cellStyles, Styles rowStyles, ResolvedSheetStyles sheetStyles,
        RowPosition rowPosition, ColumnPosition columnPosition, Styles leftStyles, Styles aboveStyles) {

    Styles styles = sheetStyles.resolve(cellStyles, rowStyles, rowPosition, columnPosition, leftStyles,
            aboveStyles);//w ww . j  ava  2  s  .c o  m

    adjustAdjacentCellStyle(cell, styles, rowPosition, columnPosition, leftStyles, aboveStyles);

    CellStyle originalStyle = cell.getCellStyle();

    CellStyle finalStyle = composeCellStyle(cell, styles);

    if (finalStyle != originalStyle) {
        cell.setCellStyle(finalStyle);
    }

    return styles;
}

From source file:com.hauldata.dbpa.file.book.XlsxTargetSheet.java

License:Apache License

private void adjustAdjacentCellStyle(Cell cell, Styles styles, RowPosition rowPosition,
        ColumnPosition columnPosition, Styles leftStyles, Styles aboveStyles) {

    if (styles == null) {
        return;/*  w  ww .  ja v a 2s . com*/
    }

    if ((leftStyles != null) && (columnPosition != ColumnPosition.LEFT)
            && (columnPosition != ColumnPosition.SINGLE) && !leftStyles.rightBorder.equals(styles.leftBorder)) {

        leftStyles.rightBorder = styles.leftBorder;

        Cell leftCell = cell.getRow().getCell(cell.getColumnIndex() - 1);

        leftCell.setCellStyle(composeCellStyle(leftCell, leftStyles));
    }

    if ((aboveStyles != null) && (rowPosition != RowPosition.HEADER) && (rowPosition != RowPosition.TOP)
            && !aboveStyles.bottomBorder.equals(styles.topBorder)) {

        aboveStyles.bottomBorder = styles.topBorder;

        Cell aboveCell = sheet.getRow(cell.getRowIndex() - 1).getCell(cell.getColumnIndex());

        aboveCell.setCellStyle(composeCellStyle(aboveCell, aboveStyles));
    }
}

From source file:com.heimaide.server.common.utils.excel.ExportExcel.java

License:Open Source License

private void initialize(String title, List<String> headerList) {
    this.wb = new SXSSFWorkbook(500);
    this.sheet = wb.createSheet("Export");
    this.styles = createStyles(wb);
    // Create title
    if (StringUtils.isNotBlank(title)) {
        Row titleRow = sheet.createRow(rownum++);
        titleRow.setHeightInPoints(30);/*w w  w . j av a2  s.com*/
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellStyle(styles.get("title"));
        titleCell.setCellValue(title);
        sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(),
                titleRow.getRowNum(), headerList.size() - 1));
    }
    // Create header
    if (headerList == null) {
        throw new RuntimeException("headerList not null!");
    }
    Row headerRow = sheet.createRow(rownum++);
    headerRow.setHeightInPoints(16);
    for (int i = 0; i < headerList.size(); i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellStyle(styles.get("header"));
        String[] ss = StringUtils.split(headerList.get(i), "**", 2);
        if (ss.length == 2) {
            cell.setCellValue(ss[0]);
            Comment comment = this.sheet.createDrawingPatriarch()
                    .createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
            comment.setString(new XSSFRichTextString(ss[1]));
            cell.setCellComment(comment);
        } else {
            cell.setCellValue(headerList.get(i));
        }
        sheet.autoSizeColumn(i);
    }
    for (int i = 0; i < headerList.size(); i++) {
        int colWidth = sheet.getColumnWidth(i) * 2;
        sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
    }
    log.debug("Initialize success.");
}

From source file:com.heimaide.server.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?// ww w .ja  v a2 s .com
 * 
 * @param row
 *            
 * @param column
 *            ?
 * @param val
 *            
 * @param align
 *            ??1?23??
 * @return ?
 */
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType, String[] constraintValue) {
    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));
            }
        }

        if (constraintValue.length > 0) {
            // ?
            // ???
            CellRangeAddressList regions = new CellRangeAddressList(row.getRowNum(), row.getRowNum(), column,
                    column);
            // ?
            XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(constraintValue);
            DataValidationHelper help = sheet.getDataValidationHelper();

            // 
            DataValidation validation = help.createValidation(constraint, regions);

            validation.createErrorBox("", "");
            validation.setShowErrorBox(true);

            // sheet
            sheet.addValidationData(validation);
        }
    } 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:com.hotaviano.tableexporter.xls.XLSExporter.java

License:Open Source License

private void createHeader(Row row, Element element, CellStyle style) {
    int index = 0;

    for (Element el : element.getChildren()) {
        Cell headerColumn = row.createCell(index);
        headerColumn.setCellStyle(style);
        headerColumn.setCellValue(el.getText());
        index++;//from   w w  w  .ja  v  a  2 s . c o  m
    }

}

From source file:com.hp.action.CalculateDistanceAction.java

public String exportExcel() {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    user = (User) session.getAttribute("USER");

    //Authorize/*w  w  w .j  av a  2 s.  c  o m*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    //GET DATA
    locationDistanceList = (List<LocationDistance>) session.getAttribute("locationDistanceList");

    if (locationDistanceList == null)
        return INPUT;

    String fileInput = ServletActionContext.getServletContext().getRealPath("/db_exports/");
    String start = (String) session.getAttribute("startDate");
    String end = (String) session.getAttribute("endDate");

    //
    //Write
    HSSFWorkbook workBook = new HSSFWorkbook();
    HSSFSheet sheet = workBook.createSheet("Qung ?ng");
    //sheet.autoSizeColumn(200);
    sheet.setColumnWidth(0, 1000);
    sheet.setDefaultColumnWidth(20);

    //TakeOrder title
    for (int i = 1; i < 2; i++) {
        //
        Row rowstart = sheet.createRow(0);

        //Row Title
        Row row0 = sheet.createRow(i);
        row0.setHeight((short) 500);
        Cell cell0 = row0.createCell(0);

        //Merge for title
        sheet.addMergedRegion(new CellRangeAddress(i, //first row (0-based)
                i, //last row  (0-based)
                0, //first column (0-based)
                4 //last column  (0-based)
        ));
        //CellUtil.setAlignment(cell0, workBook, CellStyle.ALIGN_CENTER);
        CellStyle cellStyle = workBook.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);

        //font
        Font headerFont = workBook.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeight((short) 250);
        cellStyle.setFont(headerFont);

        cell0.setCellStyle(cellStyle);
        cell0.setCellValue("Bo co Qung ?ng");

        //Row date
        Row row1 = sheet.createRow(i + 1);
        //row1.setHeight((short)500);
        Cell cell1 = row1.createCell(0);

        //Merge for title
        sheet.addMergedRegion(new CellRangeAddress(i + 1, //first row (0-based)
                i + 1, //last row  (0-based)
                0, //first column (0-based)
                4 //last column  (0-based)
        ));
        CellStyle cellAlign = workBook.createCellStyle();
        cellAlign.setAlignment(CellStyle.ALIGN_CENTER);
        cell1.setCellStyle(cellAlign);

        if (start == null)
            start = "";
        if (end == null)
            end = "";
        cell1.setCellValue("T ngy: " + start + " - ?n ngy: " + end);

        //Row Header
        Row row = sheet.createRow(4);
        int cellnum = 0;

        for (Object obj : titleArray()) {
            Cell cell = row.createCell(cellnum++);

            CellStyle style = workBook.createCellStyle();
            style.setFillForegroundColor(HSSFColor.YELLOW.index);
            style.setFillPattern(CellStyle.SOLID_FOREGROUND);

            cell.setCellStyle(style);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float)
                cell.setCellValue((Float) obj);
        }

    }
    //Write TakeOrder
    for (int i = 0; i < locationDistanceList.size(); i++) {
        Row row = sheet.createRow(i + 5);
        int cellnum = 0;

        //Cell 0 - stt
        Cell cell0 = row.createCell(cellnum++);
        cell0.setCellValue(i + 1);

        //Set content
        for (Object obj : objectArray(locationDistanceList.get(i))) {
            Cell cell = row.createCell(cellnum++);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof Integer)
                cell.setCellValue((Integer) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float) {

                //                    CellStyle cellStyle = workBook.createCellStyle();
                //                    DataFormat format = workBook.createDataFormat();
                //                    cellStyle.setDataFormat(format.getFormat("#.#"));
                //                    cell.setCellStyle(cellStyle);

                cell.setCellValue((Float) obj);
            } else if (obj instanceof Double)
                cell.setCellValue((Double) obj);
        }

    }

    outputFile = "BaoCaoTinhQuangDuong" + start + " - " + end + ".xls";
    try {
        FileOutputStream output = new FileOutputStream(new File(fileInput + "\\" + outputFile));

        workBook.write(output);
        output.close();
        System.out.println("Excel written successfully..");
        orderFile = new FileInputStream(new File(fileInput + "\\" + outputFile));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return SUCCESS;
}