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:cn.mypandora.util.MyExcelUtil.java

License:Apache License

/**
 * Excel ????List<Map<String K,String V>>
 *
 * @param filepath    ?/*from   ww  w  . j av  a  2s . com*/
 * @param sheetTitle  Sheet??
 * @param fieldTitles Sheet????
 * @param objList     ??
 * @param fieldNames  ?objClassfield??
 */
public static void writeExcel(String filepath, String sheetTitle, String fieldTitles,
        List<Map<String, String>> objList, String fieldNames) {
    Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
    for (int j = 0; j < wbs.length; j++) {
        Workbook workbook = wbs[j];
        CreationHelper creationHelper = workbook.getCreationHelper();

        // ExcelSheet
        Sheet sheet = workbook.createSheet(sheetTitle);
        workbook.setSheetName(0, sheetTitle);

        // Sheet
        createTitle(sheet, fieldTitles);

        // Sheet?
        String[] strArray = fieldNames.split(",");
        for (int objIndex = 0; objIndex < objList.size(); objIndex++) {
            Map<String, String> map = objList.get(objIndex);
            Row row = sheet.createRow(objIndex + 1);
            for (int cellNum = 0; cellNum < strArray.length; cellNum++) {
                Cell cell = row.createCell(cellNum);
                cell.setCellType(CellType.STRING);
                if (map.get(strArray[cellNum]) != null)
                    cell.setCellValue(map.get(strArray[cellNum]).toString());
                else {
                    cell.setCellValue("");
                }
            }
        }

        // ?Excel
        saveExcelFile(workbook, filepath);
    }

}

From source file:cn.mypandora.util.MyExcelUtil.java

License:Apache License

/**
 * Excle//  w  w w . j  a va2 s  . co m
 *
 * @param filepath    ?
 * @param sheetTitle  Sheet??
 * @param fieldTitles Sheet????
 * @param objList     ??
 * @param objClass    ???
 * @param fieldNames  ?objClassfield??
 */
public static void writeExcel(String filepath, String sheetTitle, String fieldTitles, List<?> objList,
        Class<?> objClass, String fieldNames) {
    Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
    for (int j = 0; j < wbs.length; j++) {
        Workbook workbook = wbs[j];
        CreationHelper creationHelper = workbook.getCreationHelper();

        Sheet sheet = workbook.createSheet();
        workbook.setSheetName(0, sheetTitle);

        createTitle(sheet, fieldTitles);
        createBody(sheet, objList, objClass, fieldNames);
        // ?Excel
        saveExcelFile(workbook, filepath);
    }

}

From source file:cn.org.vbn.util.LinkedDropDownLists.java

License:Apache License

LinkedDropDownLists(String workbookName) {
    File file = null;/*from   w ww . j  a v  a 2s.c om*/
    FileOutputStream fos = null;
    Workbook workbook = null;
    Sheet sheet = null;
    DataValidationHelper dvHelper = null;
    DataValidationConstraint dvConstraint = null;
    DataValidation validation = null;
    CellRangeAddressList addressList = null;
    try {

        // Using the ss.usermodel allows this class to support both binary
        // and xml based workbooks. The choice of which one to create is
        // made by checking the file extension.
        if (workbookName.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook();
        } else {
            workbook = new HSSFWorkbook();
        }

        // Build the sheet that will hold the data for the validations. This
        // must be done first as it will create names that are referenced
        // later.
        sheet = workbook.createSheet("Linked Validations");
        LinkedDropDownLists.buildDataSheet(sheet);

        // Build the first data validation to occupy cell A1. Note
        // that it retrieves it's data from the named area or region called
        // CHOICES. Further information about this can be found in the
        // static buildDataSheet() method below.
        addressList = new CellRangeAddressList(0, 0, 0, 0);
        dvHelper = sheet.getDataValidationHelper();
        dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");
        validation = dvHelper.createValidation(dvConstraint, addressList);
        sheet.addValidationData(validation);

        // Now, build the linked or dependent drop down list that will
        // occupy cell B1. The key to the whole process is the use of the
        // INDIRECT() function. In the buildDataSheet(0 method, a series of
        // named regions are created and the names of three of them mirror
        // the options available to the user in the first drop down list
        // (in cell A1). Using the INDIRECT() function makes it possible
        // to convert the selection the user makes in that first drop down
        // into the addresses of a named region of cells and then to use
        // those cells to populate the second drop down list.
        addressList = new CellRangeAddressList(0, 0, 1, 1);
        dvConstraint = dvHelper.createFormulaListConstraint("INDIRECT(UPPER($A$1))");
        validation = dvHelper.createValidation(dvConstraint, addressList);
        sheet.addValidationData(validation);

        file = new File(workbookName);
        fos = new FileOutputStream(file);
        workbook.write(fos);
    } catch (IOException ioEx) {
        System.out.println("Caught a: " + ioEx.getClass().getName());
        System.out.println("Message: " + ioEx.getMessage());
        System.out.println("Stacktrace follws:.....");
        ioEx.printStackTrace(System.out);
    } finally {
        try {
            if (fos != null) {
                fos.close();
                fos = null;
            }
        } catch (IOException ioEx) {
            System.out.println("Caught a: " + ioEx.getClass().getName());
            System.out.println("Message: " + ioEx.getMessage());
            System.out.println("Stacktrace follws:.....");
            ioEx.printStackTrace(System.out);
        }
    }
}

From source file:cn.study.innerclass.PoiUtil.java

License:Open Source License

public static Workbook createHSSFWorkbook() {
    return new HSSFWorkbook();
}

From source file:co.com.codesoftware.logica.excel.ExcelLogica.java

public ExcelLogica() {
    try {/*from   w  w w .ja  va 2  s.c  o  m*/
        Context initCtx = new InitialContext();
        this.ruta = (String) initCtx.lookup("java:comp/env/RutaBaseApp");
        this.libro = new HSSFWorkbook();
        hoja = libro.createSheet();
        this.crearfuente();
        this.ruta += "excel.xls";
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:co.com.controlestatidisticoshewhart.main.VentanaPrincipal.java

private void obtenerRutaGuardarArchivo() {
    try {/*  w ww .  ja v a 2s.  c  om*/
        JFileChooser file = new JFileChooser();
        file.showSaveDialog(this);
        File guarda = file.getSelectedFile();

        if (guarda != null) {

            String nombreArchivo = guarda.getAbsolutePath() + Constante.XLS;

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet hojaUnoDatosGenerados = workbook.createSheet(Constante.TITULO_HOJA_DATOS);
            HSSFSheet hojaDosDatosResultados = workbook.createSheet(Constante.TITULO_HOJA_RESULTADOS);

            List<Dato> datosGenerados = DatosExcelSingleton.getInstance().getListaDatosExcel();
            Map resultadosCalculo = DatosExcelSingleton.getInstance().getResultadosDeCalculo();

            HSSFRow rowhead = hojaUnoDatosGenerados.createRow((short) 0);
            /** Encabezado hoja uno. */
            rowhead.createCell(0).setCellValue(Constante.INDICE);
            rowhead.createCell(1).setCellValue(Constante.DATO_ALEATORIO);
            rowhead.createCell(2).setCellValue(Constante.SUPERA_LIMITE_INFERIOR);
            rowhead.createCell(3).setCellValue(Constante.SUPERA_LIMITE_SUPERIOR);

            HSSFRow rowheadHojaDos = hojaDosDatosResultados.createRow((short) 0);
            /** Encabezado hoja dos. */
            rowheadHojaDos.createCell(0).setCellValue(Constante.COLUMNA_LIMITE_INFERIOR);
            rowheadHojaDos.createCell(1).setCellValue(Constante.COLUMNA_LIMITE_SUPERIOR);
            rowheadHojaDos.createCell(2).setCellValue(Constante.COLUMNA_MEDIA);
            rowheadHojaDos.createCell(3).setCellValue(Constante.COLUMNA_DATOS_FUERA_LIMITE);
            rowheadHojaDos.createCell(4).setCellValue(Constante.COLUMNA_ARL);

            /**
             * Escribir en hoja uno.
             */
            HSSFRow row = null;
            int fila = 1;
            for (int i = 0; i < datosGenerados.size(); i++) {
                row = hojaUnoDatosGenerados.createRow(fila++);
                row.createCell(0).setCellValue(datosGenerados.get(i).getSecuencial());
                row.createCell(1).setCellValue(datosGenerados.get(i).getNumero());
                row.createCell(2).setCellValue(datosGenerados.get(i).isSobrePasaLimiteInferior());
                row.createCell(3).setCellValue(datosGenerados.get(i).isSobrePasaLimiteSuperior());
            }

            /** 
             * Escribir en hoja dos.
             */
            HSSFRow filaResultados = null;
            filaResultados = hojaDosDatosResultados.createRow(1);
            filaResultados.createCell(0)
                    .setCellValue(resultadosCalculo.get(Constante.LIMITE_CONTROL_INFERIOR).toString());
            filaResultados.createCell(1)
                    .setCellValue(resultadosCalculo.get(Constante.LIMITE_CONTROL_SUPERIOR).toString());
            filaResultados.createCell(2)
                    .setCellValue(resultadosCalculo.get(Constante.MEDIA_DATOS_EXTREMOS).toString());
            filaResultados.createCell(3)
                    .setCellValue(resultadosCalculo.get(Constante.CANTIDAD_DATOS_EXTREMOS).toString());
            filaResultados.createCell(4)
                    .setCellValue(resultadosCalculo.get(Constante.AVERAGE_RUN_LENGTH).toString());

            /**
             * Ajustar columnas hoja uno.
             */
            hojaUnoDatosGenerados.autoSizeColumn(0);
            hojaUnoDatosGenerados.autoSizeColumn(1);
            hojaUnoDatosGenerados.autoSizeColumn(2);
            hojaUnoDatosGenerados.autoSizeColumn(3);

            /**
             * Ajustar columnas hoja dos.
             */
            hojaDosDatosResultados.autoSizeColumn(0);
            hojaDosDatosResultados.autoSizeColumn(1);
            hojaDosDatosResultados.autoSizeColumn(2);
            hojaDosDatosResultados.autoSizeColumn(3);
            hojaDosDatosResultados.autoSizeColumn(4);

            try (FileOutputStream fileOut = new FileOutputStream(nombreArchivo)) {
                workbook.write(fileOut);
            } catch (Exception e) {
                throw new Exception("Error al escribir el archivo. Intente de nuevo.");
            }
            mensaje(Constante.ARCHIVO_EXCEL_CON_RESULTADOS_GENERADO);
            JOptionPane.showMessageDialog(null, "El archivo se ha guardado Exitosamente.", "Informacin",
                    JOptionPane.INFORMATION_MESSAGE);
        } else {
            mensaje("Debe seleccionar una ruta valida e ingresar el nombre del archivo.");
            JOptionPane.showMessageDialog(null,
                    "Debe seleccionar una ruta valida e ingresar el nombre del archivo.", "Advertencia",
                    JOptionPane.WARNING_MESSAGE);
        }
    } catch (Exception ex) {
        mensaje("Error al generar el archivo.Intentelo de nuevo.");
        JOptionPane.showMessageDialog(null, "Su archivo no se ha guardado", "Advertencia",
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:co.foldingmap.data.ExcelDataConnector.java

License:Open Source License

/**
 * Opens the Excel Workbook to be used by this class.
 * // w w  w . j av a2  s . c  o m
 * @param workBookFile
 * @return 
 */
private Workbook openWorkBook(File workBookFile) {
    FileInputStream openedStream;
    Workbook openedWorkbook = new HSSFWorkbook();

    try {
        openedStream = new FileInputStream(workBookFile);

        if (workBookFile.getName().endsWith(".xls")) {
            //old file type
            openedWorkbook = new HSSFWorkbook(openedStream);
        } else if (workBookFile.getName().endsWith(".xlsx")) {
            //new file type
            openedWorkbook = new XSSFWorkbook(openedStream);
        } else {
            //unknown file type
        }
    } catch (Exception e) {
        Logger.log(Logger.ERR, "Error ExcelDataConnector.openWorkBook(File) - " + e);
    }

    return openedWorkbook;
}

From source file:co.turnus.analysis.data.bottlenecks.io.XlsAlgoBottlenecksDataWriter.java

License:Open Source License

public void write(AlgoBottlenecksData report, File file) {
    try {//www.  ja va 2  s  . c om
        HSSFWorkbook workbook = new HSSFWorkbook();

        titleFont = workbook.createFont();
        titleFont.setFontName("Arial");
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("m/d/yy h:mm"));

        HotspotsDataAnalyser analyzer = new HotspotsDataAnalyser(report);
        writeSummary(workbook, report.getNetwork(), analyzer);
        writeActorClassesTable(workbook, analyzer);
        writeActorsTable(workbook, analyzer);
        writeActionActorClassTable(workbook, analyzer);
        writeActionActorTable(workbook, analyzer);

        // check if there are also impact analysis data
        ImpactData impactData = report.getImpactData();
        if (impactData != null) {
            writeImpactAnalysis(workbook, impactData);
        }

        OutputStream out = new FileOutputStream(file);
        out = new BufferedOutputStream(out);
        workbook.write(out);
        out.close();
    } catch (Exception e) {
        throw new TurnusRuntimeException("Error writing the excel file " + file, e.getCause());
    }

}

From source file:co.turnus.analysis.data.buffers.io.XlsBufferMinimizationDataWriter.java

License:Open Source License

public void write(BufferMinimizationData report, File file) {
    try {//from w w w .java2  s.co  m
        HSSFWorkbook workbook = new HSSFWorkbook();

        titleFont = workbook.createFont();
        titleFont.setFontName("Arial");
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        int solutionId = 1;
        for (BuffersData data : report.getBuffersData()) {
            writeData(workbook, data, report.getNetwork(), report.getAlgorithm(), solutionId++);
        }

        OutputStream out = new FileOutputStream(file);
        out = new BufferedOutputStream(out);
        workbook.write(out);
        out.close();
    } catch (Exception e) {
        throw new TurnusRuntimeException("Error writing the excel file " + file, e.getCause());
    }
}

From source file:co.turnus.analysis.data.partitioning.io.XlsPartitioningDataWriter.java

License:Open Source License

public void write(PartitioningData report, File file) {
    try {/*w  ww  .  jav  a  2  s.  c  om*/
        HSSFWorkbook workbook = new HSSFWorkbook();

        titleFont = workbook.createFont();
        titleFont.setFontName("Arial");
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        int solutionId = 1;
        for (PartitionsData data : report.getPartitionsData()) {
            writeData(workbook, data, report.getNetwork(), report.getAlgorithm(), solutionId++);
        }

        OutputStream out = new FileOutputStream(file);
        out = new BufferedOutputStream(out);
        workbook.write(out);
        out.close();
    } catch (Exception e) {
        throw new TurnusRuntimeException("Error writing the excel file " + file, e.getCause());
    }

}