Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook HSSFWorkbook

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook HSSFWorkbook

Introduction

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

Prototype

public HSSFWorkbook() 

Source Link

Document

Creates new HSSFWorkbook from scratch (start here!)

Usage

From source file:action.CustomerReciptAction.java

public String customerRecipt() throws IOException {

    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    HttpSession session = request.getSession();
    CustomerOrder customerOrder = (CustomerOrder) request.getSession().getAttribute("orderRecordMap");
    Customer customer = (Customer) request.getSession().getAttribute("customerMap");
    List<ProductOrder> orderedProducts = (List<ProductOrder>) request.getSession()
            .getAttribute("orderedProductsMap");
    List<Product> products = (List<Product>) request.getSession().getAttribute("productsMap");

    HSSFWorkbook workBook = new HSSFWorkbook();
    SalesReport salesReport = new SalesReport();
    /** Date Time Format for Time Stamp */
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm");
    String dateFormat = simpleDateFormat.format(new Date());
    /**File Name for XLS File */
    String fileName = "Recipt_" + dateFormat;

    salesReport.customerReport(customerOrder, customer, orderedProducts, products, workBook, request);
    response.setContentType("application/vnd.ms-excel");
    /** Change attachment into inline, inorder to open the excel file in Readonly mode */
    response.setHeader("Content-disposition", "inline;filename=" + fileName + ".xls");

    workBook.write(response.getOutputStream());
    response.getOutputStream().close();//from  w w  w . ja  v a 2s .com
    return SUCCESS;
}

From source file:adams.data.io.output.ExcelSpreadSheetWriter.java

License:Open Source License

/**
 * Performs the actual writing. The caller must ensure that the writer gets
 * closed.//from  ww w.  j a  v  a2s.  c o  m
 *
 * @param content   the spreadsheet to write
 * @param out      the writer to write the spreadsheet to
 * @return      true if successfully written
 */
@Override
protected boolean doWrite(SpreadSheet[] content, OutputStream out) {
    boolean result;
    Workbook workbook;
    Sheet sheet;
    Row row;
    adams.data.spreadsheet.Row spRow;
    adams.data.spreadsheet.Cell spCell;
    Cell cell;
    int i;
    int n;
    int count;
    CellStyle styleDate;
    CellStyle styleDateTime;
    CellStyle styleTime;
    HashSet<String> names;
    String name;

    result = true;

    try {
        if (getWriteOOXML())
            workbook = new XSSFWorkbook();
        else
            workbook = new HSSFWorkbook();
        styleDate = ExcelHelper.getDateCellStyle(workbook, Constants.DATE_FORMAT);
        styleDateTime = ExcelHelper.getDateCellStyle(workbook, Constants.TIMESTAMP_FORMAT);
        styleTime = ExcelHelper.getDateCellStyle(workbook, Constants.TIME_FORMAT);

        count = 0;
        names = new HashSet<>();
        for (SpreadSheet cont : content) {
            if (m_Stopped)
                return false;

            sheet = workbook.createSheet();
            if (cont.getName() != null) {
                name = cont.getName().replace("'", "");
                if (names.contains(name))
                    name += (count + 1);
            } else {
                name = m_SheetPrefix + (count + 1);
            }
            names.add(name);
            workbook.setSheetName(count, name);

            // header
            row = sheet.createRow(0);
            for (i = 0; i < cont.getColumnCount(); i++) {
                cell = row.createCell(i);
                cell.setCellValue(cont.getHeaderRow().getCell(i).getContent());
            }

            // data
            for (n = 0; n < cont.getRowCount(); n++) {
                if (m_Stopped)
                    return false;
                row = sheet.createRow(n + 1);
                spRow = cont.getRow(n);
                for (i = 0; i < cont.getColumnCount(); i++) {
                    cell = row.createCell(i);
                    spCell = spRow.getCell(i);
                    if ((spCell == null) || spCell.isMissing()) {
                        if (m_MissingValue.length() > 0)
                            cell.setCellValue(m_MissingValue);
                        else
                            cell.setCellType(Cell.CELL_TYPE_BLANK);
                        continue;
                    }

                    if (spCell.isFormula() && !m_OutputAsDisplayed) {
                        cell.setCellFormula(spCell.getFormula().substring(1));
                    } else {
                        if (spCell.isDate()) {
                            cell.setCellValue(spCell.toDate());
                            cell.setCellStyle(styleDate);
                        } else if (spCell.isTime()) {
                            cell.setCellValue(spCell.toTime());
                            cell.setCellStyle(styleTime);
                        } else if (spCell.isDateTime()) {
                            cell.setCellValue(spCell.toDateTime());
                            cell.setCellStyle(styleDateTime);
                        } else if (spCell.isNumeric()) {
                            cell.setCellValue(Utils.toDouble(spCell.getContent()));
                        } else {
                            cell.setCellValue(spCell.getContent());
                        }
                    }
                }
            }

            // next sheet
            count++;
        }

        // save
        workbook.write(out);
    } catch (Exception e) {
        result = false;
        getLogger().log(Level.SEVERE, "Failed writing spreadsheet data", e);
    }

    return result;
}

From source file:Adicionales.Abrir_xml.java

private boolean guardarArcXls(String strNomArc, List<String> archivos) {
    boolean blnRes = true;

    try {//  w  ww.j  a  v a2 s. c o  m
        // Se crea un nuevo libro de trabajo de EXCEL
        HSSFWorkbook workbook = new HSSFWorkbook();
        for (String archivo_n : archivos) {
            //cargamos el contenido del n-simo contenido
            File fileXML = new File(archivo_n);
            // Definimos una nueva instancia de un API para generar arbol XML
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // Definimos nuevo arbol XML
            DocumentBuilder builder = factory.newDocumentBuilder();
            // Representamos el archivo XML especificado en el arbol
            Document document = builder.parse(fileXML);
            //System.out.println("etiquetar archivo "+archivos.indexOf(archivo_n)+" de "+nombres.size());
            ExportarEtiquetasXml(workbook, document, nombres.get(archivos.indexOf(archivo_n)));

        }
        try (FileOutputStream output = new FileOutputStream(new File(strNomArc))) {
            workbook.write(output);
        }
        Desktop.getDesktop().open(new File(strNomArc));

    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (ParserConfigurationException e) {
        System.out.println("ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
        System.out.println("SAXException " + e.getMessage());
    }

    return blnRes;
}

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);/*ww w .j  ava 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.ja v a2  s  .c o  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);// w ww .ja  va  2 s . c  om
    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 a  2 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:ambit.io.XLSFileWriter.java

License:Open Source License

public XLSFileWriter(OutputStream out) throws Exception {
    super();//from w  ww  . j av  a 2s.c  o m
    workbook = new HSSFWorkbook();
    sheet = workbook.createSheet();
    dataformat = workbook.createDataFormat();
    style = workbook.createCellStyle();
    style.setDataFormat(dataformat.getFormat("0.00"));

    this.out = out;
}

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

License:Open Source License

public XLSFileWriter(OutputStream out, boolean hssf) throws Exception {
    super();//from  ww w  .ja  v  a  2 s  . c  o m
    workbook = hssf ? new HSSFWorkbook() : new XSSFWorkbook();
    sheet = workbook.createSheet();
    dataformat = workbook.createDataFormat();
    style = workbook.createCellStyle();
    style.setDataFormat(dataformat.getFormat("0.00"));

    this.out = out;
}

From source file:android_connector.ConfigWindowController.java

/**
 * Speichert die Ergebnisse der Lufe als Excel-Tabelle.
 *
 * @author Quelle://from w ww.  j av a2 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();
    }
}