Example usage for org.apache.poi.hssf.usermodel HSSFCell setCellStyle

List of usage examples for org.apache.poi.hssf.usermodel HSSFCell setCellStyle

Introduction

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

Prototype

public void setCellStyle(HSSFCellStyle style) 

Source Link

Usage

From source file:HSSFReadWrite.java

License:Apache License

/**
 * given a filename this outputs a sample sheet with just a set of
 * rows/cells.//from   www .ja v  a  2s . com
 */
private static void testCreateSampleSheet(String outputFilename) throws IOException {
    int rownum;
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet s = wb.createSheet();
    HSSFCellStyle cs = wb.createCellStyle();
    HSSFCellStyle cs2 = wb.createCellStyle();
    HSSFCellStyle cs3 = wb.createCellStyle();
    HSSFFont f = wb.createFont();
    HSSFFont f2 = wb.createFont();

    f.setFontHeightInPoints((short) 12);
    f.setColor((short) 0xA);
    f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    f2.setFontHeightInPoints((short) 10);
    f2.setColor((short) 0xf);
    f2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    cs.setFont(f);
    cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
    cs2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    cs2.setFillPattern((short) 1); // fill w fg
    cs2.setFillForegroundColor((short) 0xA);
    cs2.setFont(f2);
    wb.setSheetName(0, "HSSF Test");
    for (rownum = 0; rownum < 300; rownum++) {
        HSSFRow r = s.createRow(rownum);
        if ((rownum % 2) == 0) {
            r.setHeight((short) 0x249);
        }

        for (int cellnum = 0; cellnum < 50; cellnum += 2) {
            HSSFCell c = r.createCell(cellnum);
            c.setCellValue(rownum * 10000 + cellnum + (((double) rownum / 1000) + ((double) cellnum / 10000)));
            if ((rownum % 2) == 0) {
                c.setCellStyle(cs);
            }
            c = r.createCell(cellnum + 1);
            c.setCellValue(new HSSFRichTextString("TEST"));
            // 50 characters divided by 1/20th of a point
            s.setColumnWidth(cellnum + 1, (int) (50 * 8 / 0.05));
            if ((rownum % 2) == 0) {
                c.setCellStyle(cs2);
            }
        }
    }

    // draw a thick black border on the row at the bottom using BLANKS
    rownum++;
    rownum++;
    HSSFRow r = s.createRow(rownum);
    cs3.setBorderBottom(HSSFCellStyle.BORDER_THICK);
    for (int cellnum = 0; cellnum < 50; cellnum++) {
        HSSFCell c = r.createCell(cellnum);
        c.setCellStyle(cs3);
    }
    s.addMergedRegion(new CellRangeAddress(0, 3, 0, 3));
    s.addMergedRegion(new CellRangeAddress(100, 110, 100, 110));

    // end draw thick black border
    // create a sheet, set its title then delete it
    s = wb.createSheet();
    wb.setSheetName(1, "DeletedSheet");
    wb.removeSheetAt(1);

    // end deleted sheet
    FileOutputStream out = new FileOutputStream(outputFilename);
    wb.write(out);
    out.close();
}

From source file:Console.java

static public void exportToExcel(String sheetName, ArrayList headers, ArrayList data, File outputFile)
        throws HPSFException {

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(sheetName);

    int rowIdx = 0;
    short cellIdx = 0;

    // Header/*from w w  w  .j  a  v  a  2 s.  c o  m*/
    HSSFRow hssfHeader = sheet.createRow(rowIdx);
    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    for (Iterator cells = headers.iterator(); cells.hasNext();) {
        HSSFCell hssfCell = hssfHeader.createCell(cellIdx++);
        hssfCell.setCellStyle(cellStyle);
        hssfCell.setCellValue((String) cells.next());
    }
    // Data
    rowIdx = 1;
    for (Iterator rows = data.iterator(); rows.hasNext();) {
        ArrayList row = (ArrayList) rows.next();
        HSSFRow hssfRow = sheet.createRow(rowIdx++);
        cellIdx = 0;
        for (Iterator cells = row.iterator(); cells.hasNext();) {
            HSSFCell hssfCell = hssfRow.createCell(cellIdx++);
            Object o = cells.next();
            if ("class java.lang.Double".equals(o.getClass().toString())) {
                hssfCell.setCellValue((Double) o);
            } else {
                hssfCell.setCellValue((String) o);
            }

        }
    }

    wb.setSheetName(0, sheetName);
    try {
        FileOutputStream outs = new FileOutputStream(outputFile);
        wb.write(outs);
        outs.close();
        //            System.out.println("Archivo creado correctamente en " + outputFile.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
        throw new HPSFException(e.getMessage());
    }
}

From source file:Adicionales.Abrir_xml.java

private void ExportarEtiquetasXml(HSSFWorkbook workbook, Document document, String nombre) {
    System.out.println("Exportando : " + nombre);
    try {/*from  ww  w  .j  a v  a2  s  .  com*/
        HSSFSheet sheet = workbook.createSheet(tipo_comprobante + " " + (nombres.indexOf(nombre) + 1));
        System.out.println("Primera vez creada");
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFRow rowTag = sheet.createRow(0);
        HSSFRow RowData = sheet.createRow(1);
        NodeList nodeList = document.getElementsByTagName("*");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            if (element.getChildNodes().getLength() == 1 && !element.getNodeName().contains(":")) {
                if (element.getFirstChild().getNodeType() == Node.TEXT_NODE
                        && !element.getNodeName().equals("comprobante")) {
                    HSSFCell cellTag = rowTag.createCell(i);
                    cellTag.setCellValue(element.getNodeName());
                    HSSFCell cellData = RowData.createCell(i);
                    cellData.setCellValue(element.getFirstChild().getNodeValue());
                    sheet.autoSizeColumn((short) i);
                    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                    cellTag.setCellStyle(cellStyle);
                } else {
                    DocumentBuilderFactory sub_factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder sub_builder = sub_factory.newDocumentBuilder();
                    Document sub_document = sub_builder
                            .parse(new InputSource(new StringReader(element.getFirstChild().getNodeValue())));
                    NodeList sub_nodeList = sub_document.getElementsByTagName("*");
                    for (int j = 0; j < sub_nodeList.getLength(); j++) {
                        Element sub_element = (Element) sub_nodeList.item(j);
                        if (sub_element.getNodeName().equals("Signature"))
                            break;
                        if (sub_element.getChildNodes().getLength() == 1
                                && !sub_element.getNodeName().contains(":")) {
                            if (sub_element.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                                HSSFCell cellTag = rowTag.createCell(j);
                                cellTag.setCellValue(sub_element.getNodeName());
                                HSSFCell cellData = RowData.createCell(j);
                                cellData.setCellValue(sub_element.getFirstChild().getNodeValue());
                                sheet.autoSizeColumn((short) j);
                                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                                cellTag.setCellStyle(cellStyle);
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (IllegalArgumentException e) {
        JOptionPane.showMessageDialog(null, "<html>Error al exportar archivo " + nombre
                + "<br>Verificar maximo de etiquetas soportadas [255]</html>");
    } catch (ParserConfigurationException e) {
        System.out.println("ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
        System.out.println("SAXException " + e.getMessage());
    }
}

From source file:ambit.io.XLSFileWriter.java

License:Open Source License

public void writeMolecule(IMolecule molecule) {

    Object value;/*from   w  ww.j a  v  a  2 s .c  om*/

    try {
        //give it a chance to create a header just before the first write
        if (!writingStarted) {
            if (header == null)
                setHeader(molecule.getProperties());
            writeHeader();
            writingStarted = true;
        }
        HSSFRow row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
        String s;
        for (int i = 0; i < header.size(); i++) {
            value = molecule.getProperty(header.list.get(i));
            if (i == smilesIndex) {

                if (value == null) //no SMILES available
                    try {
                        value = sg.createSMILES(molecule);
                    } catch (Exception x) {
                        logger.error("Error while createSMILES\t", x.getMessage());
                        value = "";
                    }
            }

            if (value != null) {
                HSSFCell cell = row.createCell((short) (i + 1));

                if (value instanceof Number) {
                    cell.setCellStyle(style);
                    cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(((Number) value).doubleValue());
                } else {
                    try {
                        double d = Double.parseDouble(value.toString());
                        cell.setCellStyle(style);
                        cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(d);
                    } catch (Exception x) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellValue(value.toString());
                    }
                }

            }
        }
    } catch (Exception x) {
        logger.error("ERROR while writing Molecule: ", x.getMessage());
        logger.debug(x);
        x.printStackTrace();
    }
}

From source file:angiotool.SaveToExcel.java

License:Open Source License

private HSSFCell createCell(int column, Object obj, HSSFCellStyle cellStyle) {
    if (column < 0)
        column = 0;//from www .java2 s.c  o  m
    HSSFCell cell = r.createCell(column);
    if (obj instanceof String)
        cell.setCellValue(new HSSFRichTextString((String) obj));
    else if (obj instanceof Double)
        cell.setCellValue((Double) obj);
    else if (obj instanceof Integer)
        cell.setCellValue((Integer) obj);
    else if (obj instanceof Long)
        cell.setCellValue((Long) obj);
    cell.setCellStyle(cellStyle);

    return cell;
}

From source file:at.htlpinkafeld.beans.AlleAbwesenheitenBean.java

/**
 * xls post processing// w w  w  .j  a  va 2 s.  c  om
 *
 * @param document xls document
 */
public void postProcessXLS(Object document) {
    HSSFWorkbook wb = (HSSFWorkbook) document;
    HSSFSheet sheet = wb.getSheetAt(0);

    HSSFRow header = sheet.getRow(0);

    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        HSSFCell cell = header.getCell(i);
        cell.setCellStyle(cellStyle);

        sheet.autoSizeColumn(i);
    }

    HSSFRow bottomRow = sheet.createRow(sheet.getLastRowNum() + 2);
    bottomRow.createCell(0)
            .setCellValue("Stand: " + LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));

}

From source file:at.htlpinkafeld.beans.JahresuebersichtBean.java

/**
 * post processes the XLS for creating/*from w  w  w .  j a v a  2  s .c  o m*/
 *
 * @param document xls-doc
 */
public void postProcessXLS(Object document) {
    HSSFWorkbook wb = (HSSFWorkbook) document;
    HSSFSheet sheet = wb.getSheetAt(0);

    sheet.shiftRows(0, sheet.getLastRowNum(), 2);

    HSSFRow topRow = sheet.createRow(0);

    topRow.createCell(0).setCellValue("Jahresbersicht - " + selectedYear.getYear());
    topRow.createCell(3).setCellValue("von " + selectedUser.getPersName());
    sheet.createRow(1).createCell(0).setCellValue(" ");

    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));

    HSSFRow header = sheet.getRow(2);
    HSSFRow footer = sheet.getRow(sheet.getLastRowNum());

    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        HSSFCell cell = header.getCell(i);
        cell.setCellStyle(cellStyle);

        cell = footer.getCell(i);
        cell.setCellStyle(cellStyle);

        sheet.autoSizeColumn(i);
    }

    HSSFRow bottomRow = sheet.createRow(sheet.getLastRowNum() + 2);
    bottomRow.createCell(0)
            .setCellValue("Stand: " + LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));

}

From source file:at.htlpinkafeld.beans.UserDetailsBean.java

public void postProcessXLS(Object document) {
        HSSFWorkbook wb = (HSSFWorkbook) document;
        HSSFSheet sheet = wb.getSheetAt(0);

        sheet.shiftRows(0, sheet.getLastRowNum(), 2);

        HSSFRow topRow = sheet.createRow(0);

        topRow.createCell(0)//  w ww  . j av  a  2 s .  c om
                .setCellValue("Monatsbersicht - " + selectedDate.format(DateTimeFormatter.ofPattern("MM.yyyy")));
        topRow.createCell(7).setCellValue("von " + selectedUser);
        sheet.createRow(1).createCell(0).setCellValue(" ");

        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));

        HSSFRow header = sheet.getRow(2);
        HSSFRow footer = sheet.getRow(sheet.getLastRowNum());

        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
            HSSFCell cell = header.getCell(i);
            cell.setCellStyle(cellStyle);

            cell = footer.getCell(i);
            cell.setCellStyle(cellStyle);

            sheet.autoSizeColumn(i);
        }

        HSSFRow bottomRow = sheet.createRow(sheet.getLastRowNum() + 2);
        bottomRow.createCell(0)
                .setCellValue("Stand: " + LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));

    }

From source file:attandance.standalone.manager.AttandanceManager.java

private void outputAttandance(List<LateRecord> lates, List<AbsenceRecord> absences) {
    // webbookExcel  
    HSSFWorkbook wb = new HSSFWorkbook();
    // webbooksheet,Excelsheet  
    HSSFSheet sheet = wb.createSheet("");
    int width = ((int) (20 * 1.14388)) * 256;
    sheet.setColumnWidth(0, width);//w ww . j a  v a 2 s  . c  o m
    sheet.setColumnWidth(1, width);
    sheet.setColumnWidth(2, width);
    sheet.setColumnWidth(3, width);
    // sheet0,??poiExcel?short  
    HSSFRow row = sheet.createRow((int) 0);
    // ?   
    HSSFCellStyle style = wb.createCellStyle();
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // ?  

    HSSFCell cell = row.createCell((short) 0);
    cell.setCellValue("??");
    cell.setCellStyle(style);
    cell = row.createCell((short) 1);
    cell.setCellValue("");
    cell.setCellStyle(style);
    cell = row.createCell((short) 2);
    cell.setCellValue("?");
    cell.setCellStyle(style);
    cell = row.createCell((short) 3);
    cell.setCellValue("?");
    cell.setCellStyle(style);

    // ? ??   
    int i = 0;
    for (; i < lates.size(); i++) {
        row = sheet.createRow((int) i + 1);
        LateRecord lateStaff = lates.get(i);
        // ?  
        row.createCell((short) 0).setCellValue(lateStaff.getStaffName());
        row.createCell((short) 1).setCellValue(lateStaff.getCaculateDateString());
        cell = row.createCell((short) 2);
        cell.setCellValue(new SimpleDateFormat(DateHelper.DATE_FORMAT).format(lateStaff.getLateDate()));
        row.createCell((short) 3).setCellValue(lateStaff.getLateTimeDesc());
    }
    for (int j = 0; j < absences.size(); j++) {
        row = sheet.createRow((int) i + j + 1);
        AbsenceRecord absenceStaff = absences.get(j);
        // ?  
        row.createCell((short) 0).setCellValue(absenceStaff.getStaffName());
        row.createCell((short) 1).setCellValue(absenceStaff.getCaculateDateString());
        cell = row.createCell((short) 2);
        cell.setCellValue(
                new SimpleDateFormat(DateHelper.ONLY_DATE_FORMAT).format(absenceStaff.getAbsenceDate()));
        row.createCell((short) 3).setCellValue("?");
    }
    // ?  
    try {
        String fileName = "C:/xhuxing-private/" + new Date(System.currentTimeMillis()).getMonth()
                + ".xls";
        FileOutputStream fout = new FileOutputStream(fileName);
        wb.write(fout);
        fout.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileExcelParser.java

License:Open Source License

public void export(Date date, DiveProfile diveProfile, File file) throws IOException {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(UIAgent.getInstance().getExportFormatDateHoursFull().format(date));

    HSSFCellStyle cellStyle = wb.createCellStyle();
    HSSFFont font = wb.createFont();/*from w  w w  . j a  va 2  s. co  m*/
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    cellStyle.setFont(font);

    int rowIndex = 0;
    int colIndex = 0;
    HSSFRow row = sheet.createRow(rowIndex++);
    HSSFCell cell = row.createCell(colIndex++);
    cell.setCellValue("Time (s)");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Depth (m)");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Ascent Warning");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Bottom Time Warning");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Deco Ceiling Warning");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Deco Entry");
    cell.setCellStyle(cellStyle);

    Map<Double, Double> entries = diveProfile.getDepthEntries();
    List<Double> seconds = new ArrayList<Double>(entries.keySet());
    Collections.sort(seconds);
    for (Double time : seconds) {
        colIndex = 0;
        row = sheet.createRow(rowIndex++);
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_NUMERIC).setCellValue(time);
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_NUMERIC).setCellValue(entries.get(time));
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_BOOLEAN)
                .setCellValue(diveProfile.getAscentWarnings().contains(time));
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_BOOLEAN)
                .setCellValue(diveProfile.getRemainingBottomTimeWarnings().contains(time));
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_BOOLEAN)
                .setCellValue(diveProfile.getDecoCeilingWarnings().contains(time));
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_BOOLEAN)
                .setCellValue(diveProfile.getDecoEntries().contains(time));
    }

    for (int i = 0; i <= colIndex; i++) {
        sheet.autoSizeColumn(i);
    }

    FileOutputStream fileOut = new FileOutputStream(file);
    wb.write(fileOut);
    fileOut.close();
}