Example usage for org.apache.poi.ss.usermodel Row createCell

List of usage examples for org.apache.poi.ss.usermodel Row createCell

Introduction

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

Prototype

Cell createCell(int column);

Source Link

Document

Use this to create new cells within the row and return it.

Usage

From source file:Almacen.Existencias.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(this.usr, 0);
    h.session(sessionPrograma);/*  w w  w .ja va 2  s  . com*/
    javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
    jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
    String ruta = null;
    if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
        ruta = jF1.getSelectedFile().getAbsolutePath();
        if (ruta != null) {
            File archivoXLS = new File(ruta + ".xls");
            try {
                if (archivoXLS.exists())
                    archivoXLS.delete();
                archivoXLS.createNewFile();
                Workbook libro = new HSSFWorkbook();
                FileOutputStream archivo = new FileOutputStream(archivoXLS);
                Sheet hoja = libro.createSheet("Existencias Articulos");
                for (int ren = 0; ren < (t_datos.getRowCount() + 1); ren++) {
                    Row fila = hoja.createRow(ren);
                    for (int col = 0; col < t_datos.getColumnCount(); col++) {
                        Cell celda = fila.createCell(col);
                        if (ren == 0) {
                            celda.setCellValue(t_datos.getColumnName(col));
                        } else {
                            try {
                                celda.setCellValue(t_datos.getValueAt(ren - 1, col).toString());
                            } catch (Exception e) {
                                celda.setCellValue("");
                            }
                        }
                    }
                }
                libro.write(archivo);
                archivo.close();
                Desktop.getDesktop().open(archivoXLS);
            } catch (Exception e) {
                System.out.println(e);
                JOptionPane.showMessageDialog(this,
                        "No se pudo realizar el reporte si el archivo esta abierto");
            }
        }
    }
}

From source file:Almacen.Reporte2.java

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(this.usr, 0);
    h.session(sessionPrograma);//from  w w  w.j  ava2s .  co m
    javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
    jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
    String ruta = null;
    if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
        ruta = jF1.getSelectedFile().getAbsolutePath();
        if (ruta != null) {
            File archivoXLS = new File(ruta + ".xls");
            try {
                if (archivoXLS.exists())
                    archivoXLS.delete();
                archivoXLS.createNewFile();
                Workbook libro = new HSSFWorkbook();
                FileOutputStream archivo = new FileOutputStream(archivoXLS);
                Sheet hoja = libro.createSheet("reporte2");
                for (int ren = 0; ren < (t_datos1.getRowCount() + 1); ren++) {
                    Row fila = hoja.createRow(ren);
                    for (int col = 0; col < t_datos1.getColumnCount(); col++) {
                        Cell celda = fila.createCell(col);
                        if (ren == 0) {
                            celda.setCellValue(t_datos1.getColumnName(col));
                        } else {
                            try {
                                celda.setCellValue(t_datos1.getValueAt(ren - 1, col).toString());
                            } catch (Exception e) {
                                celda.setCellValue("");
                            }
                        }
                    }
                }
                libro.write(archivo);
                archivo.close();
                Desktop.getDesktop().open(archivoXLS);
            } catch (Exception e) {
                System.out.println(e);
                JOptionPane.showMessageDialog(this,
                        "No se pudo realizar el reporte si el archivo esta abierto");
            }
        }
    }
}

From source file:Almacen.Reporte2.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(this.usr, 0);
    h.session(sessionPrograma);/*from  w  w  w  .j  ava2 s.co  m*/
    javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
    jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
    String ruta = null;
    if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
        ruta = jF1.getSelectedFile().getAbsolutePath();
        if (ruta != null) {
            File archivoXLS = new File(ruta + ".xls");
            try {
                if (archivoXLS.exists())
                    archivoXLS.delete();
                archivoXLS.createNewFile();
                Workbook libro = new HSSFWorkbook();
                FileOutputStream archivo = new FileOutputStream(archivoXLS);
                Sheet hoja = libro.createSheet("reporte1");
                for (int ren = 0; ren < (t_datos.getRowCount() + 1); ren++) {
                    Row fila = hoja.createRow(ren);
                    for (int col = 0; col < t_datos.getColumnCount(); col++) {
                        Cell celda = fila.createCell(col);
                        if (ren == 0) {
                            celda.setCellValue(t_datos.getColumnName(col));
                        } else {
                            try {
                                celda.setCellValue(t_datos.getValueAt(ren - 1, col).toString());
                            } catch (Exception e) {
                                celda.setCellValue("");
                            }
                        }
                    }
                }
                libro.write(archivo);
                archivo.close();
                Desktop.getDesktop().open(archivoXLS);
            } catch (Exception e) {
                System.out.println(e);
                JOptionPane.showMessageDialog(this,
                        "No se pudo realizar el reporte si el archivo esta abierto");
            }
        }
    }
}

From source file:Almacen.Reporte2.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(this.usr, 0);
    h.session(sessionPrograma);//from  w w  w.j a  v  a2  s .  co  m
    javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
    jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
    String ruta = null;
    if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
        ruta = jF1.getSelectedFile().getAbsolutePath();
        if (ruta != null) {
            File archivoXLS = new File(ruta + ".xls");
            try {
                if (archivoXLS.exists())
                    archivoXLS.delete();
                archivoXLS.createNewFile();
                Workbook libro = new HSSFWorkbook();
                FileOutputStream archivo = new FileOutputStream(archivoXLS);
                Sheet hoja = libro.createSheet("reporte1");
                for (int ren = 0; ren < (t_datos2.getRowCount() + 1); ren++) {
                    Row fila = hoja.createRow(ren);
                    for (int col = 0; col < t_datos2.getColumnCount(); col++) {
                        Cell celda = fila.createCell(col);
                        if (ren == 0) {
                            celda.setCellValue(t_datos2.getColumnName(col));
                        } else {
                            try {
                                celda.setCellValue(t_datos2.getValueAt(ren - 1, col).toString());
                            } catch (Exception e) {
                                celda.setCellValue("");
                            }
                        }
                    }
                }
                libro.write(archivo);
                archivo.close();
                Desktop.getDesktop().open(archivoXLS);
            } catch (Exception e) {
                System.out.println(e);
                JOptionPane.showMessageDialog(this,
                        "No se pudo realizar el reporte si el archivo esta abierto");
            }
        }
    }
}

From source file:ambit2.core.io.XLSFileWriter.java

License:Open Source License

public void writeHeader() throws IOException {
    Row row = sheet.createRow((short) 0);
    for (int i = 0; i < header.size(); i++) {
        row.createCell((short) (i + 1)).setCellValue(header.list.get(i).toString());
    }/*from   w w  w. j av a  2s.co m*/

    logger.fine("\tHeader written\t" + header);
}

From source file:ambit2.core.io.XLSFileWriter.java

License:Open Source License

public void writeMolecule(IMolecule molecule) {

    Object value;/*from  www. j  a v  a  2  s. c  o  m*/

    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;
        }
        Row 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.log(Level.WARNING, "Error while createSMILES\t", x);
                        value = "";
                    }
            }

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

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

            }
        }
    } catch (Exception x) {
        logger.log(Level.WARNING, "ERROR while writing Molecule: ", x);
    }
}

From source file:android_connector.ConfigWindowController.java

/**
 * Speichert die Ergebnisse der Lufe als Excel-Tabelle.
 *
 * @author Quelle://from  w  w w.ja v a 2  s. co m
 * http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/
 * @param programmende True, wenn das Programm beendet werden soll, sonst
 * false.
 *
 */
public void printResults(boolean programmende) {
    /**
     * Zahl der Messtore.
     */
    int tore = Integer.parseInt(messtore.getText());
    /**
     * Gibt die gespeicherten Werte der DB an. Jedes Unterarray
     * reprsentiert einen Datensatz. Der zweite Index ist bei 0 die
     * Startnummer, 1 der Name, 2 die Kategorie, 3 Lauf 1, 4 Lauf 2.
     */
    String[][] werte = (new MySQLConnection(host.getText(), port.getText(), db.getText(), user.getText(),
            pw.getText(), null)).getAuswertung(starter, tore);
    //FileChooser einsetzen, um Speicherort zu ermitteln
    FileChooser fc = new FileChooser();
    //Titel anzeigen
    fc.setTitle("Speicherort fr die Auswertung:");
    //standardmig im Home-Verzeichnis starten
    fc.setInitialDirectory(new File(System.getProperty("user.home")));
    //Alle-Dateien-Filter entfernen
    fc.setSelectedExtensionFilter(null);
    //FileFilter fr Exceldateien hinzufgen
    //nur "alte" Excel-Dateien knnen geschrieben werden!
    fc.getExtensionFilters()
            .addAll(new FileChooser.ExtensionFilter("Microsoft Excel 1997-2003 Dokument (.xls)", "*.xls"));
    //Dateien einlesen
    File returnVal = fc.showSaveDialog(primaryStage);
    //prfen, ob Datei zurckgegeben --> eine gewhlt; muss aber nicht existieren
    if (returnVal != null) {
        /**
         * Reprsentation der Excel-Datei.
         */
        HSSFWorkbook workbook = new HSSFWorkbook();
        /**
         * Alle Kategorien, die angegeben sind.
         */
        List<String> kategorien = getKategorien();
        //alle Kategorien durchgehen, fr alle eine Mappe der DB fllen.
        for (String kategorie : kategorien) {
            /**
             * Reprsentiert die Mappe, in der die Daten landen.
             */
            HSSFSheet sheet;
            //Prfen, ob die Lnge des Kategorienamens zwischen 1 und 31 liegt --> sonst ungltig
            if (!kategorie.isEmpty() && kategorie.length() < 31) {
                //wenn ja: Kategoriename ist Mappenname
                sheet = workbook.createSheet(kategorie);
                //sonst: Standardname
            } else {
                sheet = workbook.createSheet("namenlose Kategorie");
            }

            Map<String, List<String>> data = new HashMap<String, List<String>>();
            List<String> label = new ArrayList<>();
            label.add("Startnummer");
            label.add("Name");
            label.add("Kategorie");
            label.add("reine Laufzeit- Lauf 1");
            label.add("Gesamtstrafen- Lauf 1");
            label.add("Laufzeit insgesamt- Lauf 1");
            for (int i = 0; i < tore; i++) {
                label.add("Strafe Tor " + (i + 1));
            }
            label.add("reine Laufzeit- Lauf 2");
            label.add("Gesamtstrafen- Lauf 2");
            label.add("Laufzeit insgesamt- Lauf 2");
            for (int i = 0; i < tore; i++) {
                label.add("Strafe Tor " + (i + 1));
            }
            data.put("0", label);

            for (int i = 0; i < werte.length; i++) {
                //data.put(""+(i+2), werte[i]);
                if (werte[i][2] != null) {
                    if (werte[i][2].equals(kategorie)) {
                        List<String> angaben = new ArrayList<>();
                        angaben.add(werte[i][0]);
                        angaben.add(werte[i][1]);
                        angaben.add(werte[i][2]);
                        String lauf1 = werte[i][3];
                        if (werte[i][3] != null && !werte[i][3].isEmpty()) {
                            angaben.addAll(extractList(lauf1));
                        }
                        if (werte[i][4] != null && !werte[i][4].isEmpty()) {
                            angaben.addAll(extractList(werte[i][4]));
                        }
                        data.put("" + (i + 1), angaben);
                    }
                }
            }
            Set<String> keyset = data.keySet();
            int rownum = 0;
            for (String key : keyset) {
                Row row = sheet.createRow(rownum++);
                List<String> objArr = data.get(key);
                int cellnum = 0;
                for (Object obj : objArr) {
                    Cell cell = row.createCell(cellnum++);
                    if (obj instanceof Date) {
                        cell.setCellValue((Date) obj);
                    } else if (obj instanceof Boolean) {
                        cell.setCellValue((Boolean) obj);
                    } else if (obj instanceof String) {
                        cell.setCellValue((String) obj);
                    } else if (obj instanceof Double) {
                        cell.setCellValue((Double) obj);
                    }
                }
            }
            for (int i = 0; i < 9 + 2 * tore; i++) {
                sheet.autoSizeColumn(i);
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(returnVal);
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully..");
            out = new FileOutputStream(System.getProperty("user.home") + "/Kanu-s.a.M.-Notfall.xls");
            workbook.write(out);
            out.close();

        } catch (FileNotFoundException e) {
            MySQLConnection.staticExceptionDialog(e, "Schreibfehler",
                    "Auswertung konnte nicht geschrieben werden",
                    "Die Excel-Datei mit der Auswertung konnte nicht geschrieben werden. Bitte versuchen Sie es erneut!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (programmende) {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Programmende");
        alert.setHeaderText("Der Programmablauf ist beendet.");
        alert.setContentText(
                "Das Programm hat seine Aufgabe erfllt und wird nun beendet. Vielen Dank fr die Benutzung des Softwaresystems!");
        alert.showAndWait();
        Platform.exit();
    }
}

From source file:apm.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?//from w ww.  jav  a2  s  .c o m
 * @param title ?
 * @param headerList 
 */
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);
        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:apm.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?/*  w  w  w  .  j  a v  a 2s.  co m*/
 * @param row 
 * @param column ?
 * @param val 
 * @param align ??1?23??
 * @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;
}

From source file:app.DCReportsTab.java

License:Open Source License

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed

    //Blank workbook
    XSSFWorkbook workbook = new XSSFWorkbook();

    //Create a blank sheet
    XSSFSheet sheet = workbook.createSheet("Employee Data");

    //This data needs to be written (Object[])
    Map<String, Object[]> data = new TreeMap<String, Object[]>();

    PreparedStatement pst;//from  ww  w.java 2 s.  c om
    Connection con;

    String drNumber = "";
    String dateToday = "";
    String outlet = "";
    String quantity = "";
    String deliveryDate = "";
    String totalAmount = "";

    TableModel model = deliveryReceiptsTable.getModel(); //Table model
    if (model.getRowCount() != 0) {
        Row row = sheet.createRow(2);

        Row headerRow = sheet.createRow(0); //Create row at line 0
        for (int headings = 0; headings < model.getColumnCount(); headings++) { //For each column
            headerRow.createCell(headings).setCellValue(model.getColumnName(headings));//Write column name
        }

        for (int rows = 0; rows < model.getRowCount(); rows++) { //For each table row
            for (int cols = 0; cols < deliveryReceiptsTable.getColumnCount(); cols++) { //For each table column
                row.createCell(cols).setCellValue(model.getValueAt(rows, cols).toString()); //Write value
            }

            //Set the row to the next one in the sequence 
            row = sheet.createRow((rows + 3));
        }
        try {
            //Write the workbook in file system
            java.util.Date date = new java.util.Date();
            FileOutputStream out = new FileOutputStream(
                    new File("C:/Users/Jenelle/Desktop/Report" + date.getTime() + ".xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("Written successfully on disk.");
            JOptionPane.showMessageDialog(null, "Export success!", "Success", JOptionPane.PLAIN_MESSAGE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        JOptionPane.showMessageDialog(null, "Please input data to table.", "Error", JOptionPane.ERROR_MESSAGE);
    }

}