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.rapidminer.operator.io.ExcelExampleSetWriter.java

License:Open Source License

/**
 * Writes the provided {@link ExampleSet} to a XLSX formatted data sheet.
 *
 * @param wb//ww w  .j  av  a  2s.  c  o  m
 *            the workbook to use
 * @param sheet
 *            the excel sheet to write to.
 * @param dateFormat
 *            a string which describes the format used for dates.
 * @param numberFormat
 *            a string which describes the format used for numbers.
 * @param exampleSet
 *            the exampleSet to write
 * @param op
 *            needed for checkForStop
 * @throws ProcessStoppedException
 *             if the process was stopped by the user.
 * @throws WriteException
 */
private static void writeXLSXDataSheet(SXSSFWorkbook wb, Sheet sheet, String dateFormat, String numberFormat,
        ExampleSet exampleSet, Operator op) throws WriteException, ProcessStoppedException {

    Font headerFont = wb.createFont();
    headerFont.setBold(true);

    CellStyle headerStyle = wb.createCellStyle();
    headerStyle.setFont(headerFont);

    // create the header
    Iterator<Attribute> a = exampleSet.getAttributes().allAttributes();
    int columnCounter = 0;
    int rowCounter = 0;
    Row headerRow = sheet.createRow(rowCounter);
    while (a.hasNext()) {
        Attribute attribute = a.next();
        Cell headerCell = headerRow.createCell(columnCounter);
        headerCell.setCellValue(attribute.getName());
        headerCell.setCellStyle(headerStyle);
        columnCounter++;
    }
    rowCounter++;

    // body font
    Font bodyFont = wb.createFont();
    bodyFont.setBold(false);

    CreationHelper createHelper = wb.getCreationHelper();

    // number format
    CellStyle numericalStyle = wb.createCellStyle();
    numericalStyle.setDataFormat(createHelper.createDataFormat().getFormat(numberFormat));
    numericalStyle.setFont(bodyFont);

    // date format
    CellStyle dateStyle = wb.createCellStyle();
    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat(dateFormat));
    dateStyle.setFont(bodyFont);

    // create nominal cell style
    CellStyle nominalStyle = wb.createCellStyle();
    nominalStyle.setFont(bodyFont);

    // fill body
    for (Example example : exampleSet) {

        // create new row
        Row bodyRow = sheet.createRow(rowCounter);

        // iterate over attributes and save examples
        a = exampleSet.getAttributes().allAttributes();
        columnCounter = 0;
        while (a.hasNext()) {
            Attribute attribute = a.next();
            Cell currentCell = bodyRow.createCell(columnCounter);
            if (!Double.isNaN(example.getValue(attribute))) {
                if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.DATE_TIME)) {
                    Date dateValue = example.getDateValue(attribute);
                    currentCell.setCellValue(dateValue);
                    currentCell.setCellStyle(dateStyle);
                } else if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.NUMERICAL)) {
                    double numericalValue = example.getNumericalValue(attribute);
                    currentCell.setCellValue(numericalValue);
                    currentCell.setCellStyle(numericalStyle);
                } else {
                    currentCell.setCellValue(
                            stripIfNecessary(replaceForbiddenChars(example.getValueAsString(attribute))));
                    currentCell.setCellStyle(nominalStyle);
                }
            }
            columnCounter++;
        }
        rowCounter++;

        // checkForStop every 100 examples
        if (op != null && rowCounter % 100 == 0) {
            op.checkForStop();
        }
    }
}

From source file:com.report.template.LoanCalculator.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;/* w  w  w.  ja va 2s . c  om*/

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new XSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sheet = wb.createSheet("Loan Calculator");
    sheet.setPrintGridlines(false);
    sheet.setDisplayGridlines(false);

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    sheet.setColumnWidth(0, 3 * 256);
    sheet.setColumnWidth(1, 3 * 256);
    sheet.setColumnWidth(2, 11 * 256);
    sheet.setColumnWidth(3, 14 * 256);
    sheet.setColumnWidth(4, 14 * 256);
    sheet.setColumnWidth(5, 14 * 256);
    sheet.setColumnWidth(6, 14 * 256);

    createNames(wb);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(35);
    for (int i = 1; i <= 7; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    Cell titleCell = titleRow.getCell(2);
    titleCell.setCellValue("Simple Loan Calculator");
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1"));

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(4);
    cell.setCellValue("Enter values");
    cell.setCellStyle(styles.get("item_right"));

    row = sheet.createRow(3);
    cell = row.createCell(2);
    cell.setCellValue("Loan amount");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellValue("123123");
    cell.setCellStyle(styles.get("input_$"));
    cell.setAsActiveCell();

    row = sheet.createRow(4);
    cell = row.createCell(2);
    cell.setCellValue("Annual interest rate");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_%"));

    row = sheet.createRow(5);
    cell = row.createCell(2);
    cell.setCellValue("Loan period in years");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_i"));

    row = sheet.createRow(6);
    cell = row.createCell(2);
    cell.setCellValue("Start date of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_d"));

    row = sheet.createRow(8);
    cell = row.createCell(2);
    cell.setCellValue("Monthly payment");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(9);
    cell = row.createCell(2);
    cell.setCellValue("Number of payments");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")");
    cell.setCellStyle(styles.get("formula_i"));

    row = sheet.createRow(10);
    cell = row.createCell(2);
    cell.setCellValue("Total interest");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(11);
    cell = row.createCell(2);
    cell.setCellValue("Total cost of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    // Write the output to a file
    String file = "loan-calculator.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:com.repository2excel.Main.java

License:Apache License

/**
 * @param args//from   w w  w.j  a  v a 2s. c om
 */
@SuppressWarnings("deprecation")
public static void main(String[] args) {
    String xmlRepositoryDefFilePath = "";

    /** Read user input */
    Scanner scnr = new Scanner(System.in);
    System.out.println("Enter fully qualified path to customCatalog.xml:");
    try {
        xmlRepositoryDefFilePath = scnr.next();
    } catch (InputMismatchException e) {
        // TODO:
    } finally {
        scnr.close();
    }

    RepositoryDefinitionReader reader = new RepositoryDefinitionReader();
    System.out.println("Begin reading XML Repository definition file...");
    HashSet<Item> items = reader.loadRepositoryDefinition(new File(xmlRepositoryDefFilePath));
    System.out.println("Finished reading XML file!");
    if (items != null && items.size() > 0) {
        System.out.println("Preparing to export " + items.size() + " items into Excel Spreadsheet...");
        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        Sheet sh = wb.createSheet();

        /** Create cell styles */
        CellStyle style = wb.createCellStyle();
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setBorderRight(CellStyle.BORDER_THIN);

        Iterator<Item> iter = items.iterator();
        int rownum = 0;
        while (iter.hasNext()) {
            Item item = iter.next();
            Row row = sh.createRow(rownum);
            row.createCell(0, CellType.STRING).setCellValue("Item");
            row.createCell(1, CellType.STRING).setCellValue(item.getName());
            rownum++;

            row = sh.createRow(rownum);
            row.createCell(0, CellType.STRING).setCellValue("Query Cache Size");
            row.createCell(1, CellType.STRING).setCellValue(item.getQueryCacheSize());
            rownum++;

            row = sh.createRow(rownum);
            row.createCell(0, CellType.STRING).setCellValue("Item Cache Size");
            row.createCell(1, CellType.STRING).setCellValue(item.getItemCacheSize());
            rownum++;
            HashSet<Property> properties = item.getProperties();
            if (properties != null && properties.size() > 0) {
                Cell cell;
                row = sh.createRow(rownum);
                cell = row.createCell(0, CellType.STRING);
                cell.setCellStyle(style);
                cell.setCellValue("Property");

                cell = row.createCell(1, CellType.STRING);
                cell.setCellStyle(style);
                cell.setCellValue("Type");

                cell = row.createCell(2, CellType.STRING);
                cell.setCellStyle(style);
                cell.setCellValue("Readable");

                cell = row.createCell(3, CellType.STRING);
                cell.setCellStyle(style);
                cell.setCellValue("Writable");

                cell = row.createCell(4, CellType.STRING);
                cell.setCellStyle(style);
                cell.setCellValue("Hidden");

                cell = row.createCell(5, CellType.STRING);
                cell.setCellStyle(style);
                cell.setCellValue("Table");

                cell = row.createCell(6, CellType.STRING);
                cell.setCellStyle(style);
                cell.setCellValue("Column");

                Iterator<Property> pIter = properties.iterator();
                while (pIter.hasNext()) {
                    rownum++;
                    row = sh.createRow(rownum);
                    Property property = pIter.next();
                    /** 0. Name */
                    cell = row.createCell(0, CellType.STRING);
                    cell.setCellStyle(style);
                    cell.setCellValue(property.getName());

                    /** 1. Data Type */
                    cell = row.createCell(1, CellType.STRING);
                    cell.setCellStyle(style);
                    cell.setCellValue(property.getDataType());

                    /** 2. Is Readable */
                    cell = row.createCell(2, CellType.STRING);
                    cell.setCellStyle(style);
                    cell.setCellValue(property.isReadable());

                    /** 3. Is Writable */
                    cell = row.createCell(3, CellType.STRING);
                    cell.setCellStyle(style);
                    cell.setCellValue(property.isWriteable());

                    /** 4. Is Hidden */
                    cell = row.createCell(4, CellType.STRING);
                    cell.setCellStyle(style);
                    cell.setCellValue(property.isHidden());

                    /** 5. Table */
                    cell = row.createCell(5, CellType.STRING);
                    cell.setCellStyle(style);
                    cell.setCellValue(property.getTable());

                    /** 6. Column */
                    cell = row.createCell(6, CellType.STRING);
                    cell.setCellStyle(style);
                    cell.setCellValue(property.getColumn());
                }
            }
            rownum++;
            rownum++;
        }

        try {
            File f = new File("test.xlsx");
            FileOutputStream out = new FileOutputStream(f);
            wb.write(out);
            out.close();
            wb.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // dispose of temporary files backing this workbook on disk
            wb.dispose();
        }
    }
}

From source file:com.respam.comniq.models.POIexcelExporter.java

License:Open Source License

public void createFile() throws IOException {
    String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output";
    File file = new File(path + File.separator + "POImovieInfo.xlsx");

    // Blank Workbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Movies");

    // Data for Labels
    Map<String, Object[]> label = new TreeMap<>();
    label.put("1", new Object[] { "Poster", "Title", "Release Date", "Metascore", "IMDB Rating", "Plot",
            "IMDB URL", "Genre", "Director", "Actors", "Rating", "Runtime" });

    // Iterate over label and write to sheet
    Set<String> keyset = label.keySet();

    // Setting Style for the Label Row
    Font font = workbook.createFont();
    font.setFontHeight((short) 240);
    font.setFontName("Courier New");
    font.setBold(true);/*from  w  ww  .  j a v a2  s  .c o m*/
    XSSFCellStyle labelStyle = workbook.createCellStyle();
    labelStyle.setWrapText(true);
    labelStyle.setFont(font);

    // Setting column widths
    sheet.setColumnWidth(0, 4000);
    sheet.setColumnWidth(1, 8500);
    sheet.setColumnWidth(2, 4000);
    sheet.setColumnWidth(3, 4000);
    sheet.setColumnWidth(4, 3500);
    sheet.setColumnWidth(5, 9500);
    sheet.setColumnWidth(6, 5000);
    sheet.setColumnWidth(7, 4000);
    sheet.setColumnWidth(8, 3500);
    sheet.setColumnWidth(9, 4000);
    sheet.setColumnWidth(10, 3000);
    sheet.setColumnWidth(11, 4000);

    // Freezing the first row
    sheet.createFreezePane(0, 1);

    // Filling each cell with Label data
    for (String key : keyset) {
        Row row = sheet.createRow(0);
        Object[] objArr = label.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            cell.setCellStyle(labelStyle);
            cell.setCellValue((String) obj);
        }
    }

    // Writing the excel file
    try {
        FileOutputStream out = new FileOutputStream(file);
        workbook.write(out);
        out.close();
        System.out.println("Excel File Created");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.respam.comniq.models.POIexcelExporter.java

License:Open Source License

public void excelWriter(JSONObject parsedObj, int rownum) throws IOException {
    String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output";
    File file = new File(path + File.separator + "POImovieInfo.xlsx");

    String thumbnailPath = System.getProperty("user.home") + File.separator + "comniq" + File.separator
            + "output" + File.separator + "thumbnails";
    File posterFile = new File(thumbnailPath + File.separator + parsedObj.get("Title") + ".jpg");

    if (!file.exists()) {
        createFile();//from  www .  jav  a2  s.  c  om
    }

    if (file.exists() && checked.equals(false)) {
        findLastRow();
    }

    try {
        FileInputStream fis = new FileInputStream(file);
        XSSFWorkbook workbook = new XSSFWorkbook(fis);

        XSSFSheet sheet = workbook.getSheet("Movies");

        Map<String, Object[]> label = new TreeMap<>();
        label.put("1",
                new Object[] { "", parsedObj.get("Title"), parsedObj.get("Released"),
                        parsedObj.get("Metascore"), parsedObj.get("imdbRating"), parsedObj.get("Plot"),
                        parsedObj.get("imdbID"), parsedObj.get("Genre"), parsedObj.get("Director"),
                        parsedObj.get("Actors"), parsedObj.get("Rated"), parsedObj.get("Runtime") });

        Set<String> keyset = label.keySet();

        // Setting Style for the Label Row

        XSSFCellStyle contentStyle = workbook.createCellStyle();
        contentStyle.setWrapText(true);
        contentStyle.setVerticalAlignment(VerticalAlignment.TOP);

        rownum = rownum + lastRow;

        if (posterFile.exists()) {
            InputStream imageStream = new FileInputStream(
                    thumbnailPath + File.separator + parsedObj.get("Title") + ".jpg");
            byte[] imageBytes = IOUtils.toByteArray(imageStream);
            pictureureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
            imageStream.close();

            CreationHelper helper = workbook.getCreationHelper();
            drawing = sheet.createDrawingPatriarch();
            anchor = helper.createClientAnchor();

        }

        for (String key : keyset) {

            Row row = sheet.createRow(rownum++);
            row.setHeight((short) 2000);
            Object[] objArr = label.get(key);
            int cellnum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellnum++);
                cell.setCellStyle(contentStyle);
                cell.setCellValue((String) obj);
            }
            if (posterFile.exists()) {
                anchor.setCol1(0);
                anchor.setRow1(rownum - 1);
                anchor.setCol2(0);
                anchor.setRow2(rownum - 1);
                Picture pict = drawing.createPicture(anchor, pictureureIdx);
                pict.resize(1, 1);
            }
        }
        FileOutputStream out = new FileOutputStream(file);
        workbook.write(out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.runwaysdk.dataaccess.io.ExcelExportSheet.java

License:Open Source License

protected void writeHeader(Sheet sheet, Drawing drawing, Row nameRow, Row labelRow, int i, ExcelColumn column,
        CellStyle boldStyle) {/*from   www. j a va  2 s .co m*/
    CreationHelper helper = sheet.getWorkbook().getCreationHelper();

    // Notify the listeners
    for (ExcelExportListener listener : listeners) {
        listener.preHeader(column);
    }

    nameRow.createCell(i).setCellValue(helper.createRichTextString(column.getAttributeName()));

    Cell cell = labelRow.createCell(i);
    cell.setCellValue(helper.createRichTextString(column.getDisplayLabel()));

    if (column.isRequired() && boldStyle != null) {
        cell.setCellStyle(boldStyle);
    }

    if (column.getDescription() != null && column.getDescription().length() > 0) {
        ClientAnchor anchor = helper.createClientAnchor();
        anchor.setDx1(0);
        anchor.setDy1(0);
        anchor.setDx2(0);
        anchor.setDy2(0);
        anchor.setCol1(0);
        anchor.setRow1(0);
        anchor.setCol2(0);
        anchor.setRow2(4);

        Comment comment = drawing.createCellComment(anchor);
        comment.setString(helper.createRichTextString(column.getDescription()));

        cell.setCellComment(comment);
    }

    sheet.autoSizeColumn((short) i);
}

From source file:com.runwaysdk.query.ExcelExporter.java

License:Open Source License

protected void populateDateCell(Row valueRow, int col, String value) {
    if (value != null && !value.equals("")) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);

        Date date = dateFormat.parse(value, new java.text.ParsePosition(0));

        // Precondition - assumes value is a valid couble.
        Cell cell = valueRow.createCell(col);
        cell.setCellValue(date);/*w w  w.  java  2s .c  o m*/
        cell.setCellStyle(this.getStyle());
    }
}

From source file:com.runwaysdk.query.ValueQueryExcelExporter.java

License:Open Source License

/**
 * Prepares a new sheet (which represents a type) in the workbook. Fills in
 * all necessary information for the sheet.
 * //from   w  ww. j  ava  2s .c  o  m
 * @return
 */
private Sheet prepareSheet() {
    OIterator<ValueObject> iterator = this.valueQuery.getIterator();

    Sheet sheet = workbook.createSheet(this.sheetName);
    Row labelRow = sheet.createRow(0);

    List<Selectable> selectableList = this.valueQuery.getSelectableRefs();

    int selectableCount = 0;
    for (Selectable selectable : selectableList) {
        if (this.includeAliases == null || this.includeAliases.size() == 0
                || this.includeAliases.contains(selectable.getUserDefinedAlias())) {
            MdAttributeConcreteDAOIF mdAttribute = selectable.getMdAttributeIF();
            labelRow.createCell(selectableCount).setCellValue(this.workbook.getCreationHelper()
                    .createRichTextString(mdAttribute.getDisplayLabel(Session.getCurrentLocale())));
            selectableCount++;
        }
    }

    int rowCount = 1;
    for (ValueObject valueObject : iterator) {
        Row valueRow = sheet.createRow(rowCount++);

        Map<String, Attribute> attributeMap = valueObject.getAttributeMap();

        selectableCount = 0;

        for (Selectable selectable : selectableList) {
            if (this.includeAliases == null || this.includeAliases.size() == 0
                    || this.includeAliases.contains(selectable.getUserDefinedAlias())) {
                String attributeName = selectable.getResultAttributeName();

                Attribute attribute = attributeMap.get(attributeName);

                String value = attribute.getValue();

                if (attribute instanceof com.runwaysdk.dataaccess.attributes.value.AttributeBoolean) {
                    com.runwaysdk.dataaccess.attributes.value.AttributeBoolean attributeBoolean = (com.runwaysdk.dataaccess.attributes.value.AttributeBoolean) attribute;

                    // exports as 1 and 0 as per #2735
                    String displayLabel;
                    if (value == null || value.trim().length() == 0) {
                        displayLabel = "";
                    } else if (attributeBoolean.getBooleanValue()) {
                        displayLabel = MdAttributeBooleanDAOIF.DB_TRUE;
                    } else {
                        displayLabel = MdAttributeBooleanDAOIF.DB_FALSE;
                    }

                    valueRow.createCell(selectableCount)
                            .setCellValue(this.workbook.getCreationHelper().createRichTextString(displayLabel));
                } else if (attribute instanceof com.runwaysdk.dataaccess.attributes.value.AttributeNumber) {
                    com.runwaysdk.dataaccess.attributes.value.AttributeNumber attributeNumber = (com.runwaysdk.dataaccess.attributes.value.AttributeNumber) attribute;

                    String numberValue = attributeNumber.getValue();

                    if (numberValue != null && !numberValue.equals("")) {
                        // Precondition - assumes value is a valid couble.
                        valueRow.createCell(selectableCount).setCellValue(Double.valueOf(numberValue));
                    }
                } else if (attribute instanceof com.runwaysdk.dataaccess.attributes.value.AttributeDate) {
                    com.runwaysdk.dataaccess.attributes.value.AttributeDate attributeDate = (com.runwaysdk.dataaccess.attributes.value.AttributeDate) attribute;

                    String dateValue = attributeDate.getValue();

                    if (dateValue != null && !dateValue.equals("")) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);

                        Date date = dateFormat.parse(dateValue, new java.text.ParsePosition(0));

                        // Precondition - assumes value is a valid couble.
                        Cell cell = valueRow.createCell(selectableCount);
                        cell.setCellValue(date);
                        cell.setCellStyle(dateStyle);
                    }
                } else if (attribute instanceof com.runwaysdk.dataaccess.attributes.value.AttributeDateTime) {
                    com.runwaysdk.dataaccess.attributes.value.AttributeDateTime attributeDate = (com.runwaysdk.dataaccess.attributes.value.AttributeDateTime) attribute;

                    String dateValue = attributeDate.getValue();

                    if (dateValue != null && !dateValue.equals("")) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATETIME_FORMAT);

                        Date date = dateFormat.parse(dateValue, new java.text.ParsePosition(0));

                        // Precondition - assumes value is a valid couble.
                        valueRow.createCell(selectableCount).setCellValue(date);
                    }
                } else if (attribute instanceof com.runwaysdk.dataaccess.attributes.value.AttributeTime) {
                    com.runwaysdk.dataaccess.attributes.value.AttributeTime attributeDate = (com.runwaysdk.dataaccess.attributes.value.AttributeTime) attribute;

                    String dateValue = attributeDate.getValue();

                    if (dateValue != null && !dateValue.equals("")) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.TIME_FORMAT);

                        Date date = dateFormat.parse(dateValue, new java.text.ParsePosition(0));

                        // Precondition - assumes value is a valid couble.
                        valueRow.createCell(selectableCount).setCellValue(date);
                    }
                } else if (attribute instanceof com.runwaysdk.dataaccess.attributes.value.AttributeChar
                        || attribute instanceof com.runwaysdk.dataaccess.attributes.value.AttributeReference) {
                    valueRow.createCell(selectableCount)
                            .setCellValue(this.workbook.getCreationHelper().createRichTextString(value));
                }

                selectableCount++;
            }
        }
    }

    return sheet;
}

From source file:com.sccl.attech.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * demo?//  w w  w .ja va 2 s.c o  m
 * @param title
 * @param headerList
 */
private void initializeDemo(String title, List<String> headerList) {

    // Create header
    if (headerList == null) {
        throw new RuntimeException("headerList not null!");
    }
    sheet.setColumnWidth(6, 6000);
    sheet.setColumnWidth(7, 6000);
    sheet.setColumnWidth(8, 6000);
    sheet.setColumnWidth(9, 4000);
    sheet.setColumnWidth(10, 4000);
    Row headerRow = sheet.getRow(24);
    headerRow.setHeightInPoints(16);

    Cell cell6 = headerRow.createCell(6);
    cell6.setCellValue("??");
    cell6.setCellStyle(this.styles.get("header"));

    Cell cell7 = headerRow.createCell(7);
    cell7.setCellValue("??");
    cell7.setCellStyle(this.styles.get("header"));

    Cell cell8 = headerRow.createCell(8);
    cell8.setCellValue("");
    cell8.setCellStyle(this.styles.get("header"));

    Cell cell9 = headerRow.createCell(9);
    cell9.setCellValue("?");
    cell9.setCellStyle(this.styles.get("header"));

    Cell cell10 = headerRow.createCell(10);
    cell10.setCellValue("");
    cell10.setCellStyle(this.styles.get("header"));
    log.debug("Initialize success.");
}

From source file:com.sccl.attech.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?/*from  w ww . java2s  . c  o  m*/
 * @param row 
 * @param column ?
 * @param val 
 * @param align ??1?23??
 * @return ?
 */
public Cell addCellStyle(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 : ""));
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
    style.setWrapText(true);
    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());
    }
    if (column == 8) {
        CellRangeAddressList regions = new CellRangeAddressList(25, 25, 8, 8);
        // ?  
        DVConstraint constraint = DVConstraint
                .createExplicitListConstraint(new String[] { "2", "3", "" });
        //   
        HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint);
        // sheet  
        data_validation.createErrorBox("Error", "Error");
        data_validation.createPromptBox("", null);
        sheet.addValidationData(data_validation);
    }
    cell.setCellStyle(style);
    return cell;
}