Example usage for org.apache.poi.ss.usermodel WorkbookFactory create

List of usage examples for org.apache.poi.ss.usermodel WorkbookFactory create

Introduction

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

Prototype

public static Workbook create(File file) throws IOException, EncryptedDocumentException 

Source Link

Document

Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and be readable.

Usage

From source file:adams.gui.tools.previewbrowser.ExcelSpreadSheetHandler.java

License:Open Source License

/**
 * Determines the number of sheets in the spreadsheet file.
 *
 * @param file   the spreadsheet file to check
 * @return      the number of sheets/*  w  ww .  ja  va 2  s  .  com*/
 */
protected int getSheetCount(File file) {
    int result;
    Workbook workbook;
    FileInputStream fis;
    BufferedInputStream input;

    input = null;
    fis = null;
    try {
        fis = new FileInputStream(file.getAbsoluteFile());
        input = new BufferedInputStream(fis);
        workbook = WorkbookFactory.create(input);
        result = workbook.getNumberOfSheets();
    } catch (Exception e) {
        result = 0;
        getLogger().log(Level.SEVERE, "Failed to determine sheet count for '" + file + "':", e);
    } finally {
        FileUtils.closeQuietly(input);
        FileUtils.closeQuietly(fis);
    }

    return result;
}

From source file:ar.edu.unrc.gametictactoe.performanceandtraining.configurations.StatisticExperiment.java

License:Open Source License

/**
 *
 * @param filePath/*w  ww.  j  a v  a 2 s.  c o  m*/
 * @param backupFiles
 * @param resultsPerFile
 * @param resultsRandom
 * @param randomPerceptronFile <p>
 * @throws IOException
 * @throws InvalidFormatException
 */
public void exportToExcel(String filePath, List<File> backupFiles, Map<File, StatisticForCalc> resultsPerFile,
        Map<File, StatisticForCalc> resultsRandom, File randomPerceptronFile)
        throws IOException, InvalidFormatException {
    InputStream inputXLSX = this.getClass()
            .getResourceAsStream("/ar/edu/unrc/gametictactoe/resources/EstadisticasTicTacToe.xlsx");
    Workbook wb = WorkbookFactory.create(inputXLSX);

    try (FileOutputStream outputXLSX = new FileOutputStream(
            filePath + "_" + dateFormater.format(dateForFileName) + "_STATISTICS" + ".xlsx")) {
        //============= imptimimos en la hoja de % Of Games Won ===================
        Sheet sheet = wb.getSheetAt(0);
        //Estilo par los titulos de las tablas
        int rowStartTitle = 0;
        int colStartTitle = 2;
        int rowStart = 1;
        int colStart = 3;
        Row rowPlayer1;
        Row rowPlayer2;
        Row rowDraw;
        // Luego creamos el objeto que se encargar de aplicar el estilo a la celda
        Font fontCellTitle = wb.createFont();
        fontCellTitle.setFontHeightInPoints((short) 10);
        fontCellTitle.setFontName("Arial");
        fontCellTitle.setBoldweight(Font.BOLDWEIGHT_BOLD);
        CellStyle CellStyleTitle = wb.createCellStyle();
        CellStyleTitle.setWrapText(true);
        CellStyleTitle.setAlignment(CellStyle.ALIGN_CENTER);
        CellStyleTitle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
        CellStyleTitle.setFont(fontCellTitle);

        // Establecemos el tipo de sombreado de nuestra celda
        CellStyleTitle.setFillBackgroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        CellStyleTitle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        loadTitle(rowStartTitle, colStartTitle, sheet, backupFiles.size(), CellStyleTitle);
        //estilo titulo finalizado

        //Estilo de celdas con los valores de las estadisticas
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setWrapText(true);
        /* We are now ready to set borders for this style */
        /* Draw a thin left border */
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        /* Add medium right border */
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        /* Add dashed top border */
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        /* Add dotted bottom border */
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        //estilo celdas finalizado
        //loadTitle(rowStartTitle, colStartTitle, sheet, backupFiles.size(), CellStyleTitle);
        rowPlayer1 = sheet.getRow(rowStart);
        rowPlayer2 = sheet.getRow(rowStart + 1);
        rowDraw = sheet.getRow(rowStart + 2);
        for (int file = 0; file < backupFiles.size(); file++) {
            Cell cellPlayer1 = rowPlayer1.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC);
            Cell cellPlayer2 = rowPlayer2.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC);
            Cell cellDraw = rowDraw.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC);
            cellPlayer1.setCellStyle(cellStyle);
            cellPlayer2.setCellStyle(cellStyle);
            cellDraw.setCellStyle(cellStyle);
            Double cellValuePlayer1 = resultsPerFile.get(backupFiles.get(file)).getWinRatePlayer1();
            Double cellValuePlayer2 = resultsPerFile.get(backupFiles.get(file)).getWinRatePlayer2();
            Double cellValueDraw = resultsPerFile.get(backupFiles.get(file)).getDrawRate();
            assert cellValuePlayer1 <= 100 && cellValuePlayer1 >= 0;
            assert cellValuePlayer2 <= 100 && cellValuePlayer2 >= 0;
            assert cellValueDraw <= 100 && cellValueDraw >= 0;
            //assert cellValueDraw + cellValuePlayer1 + cellValuePlayer2 == 100;
            cellDraw.setCellValue(cellValueDraw);
            cellPlayer1.setCellValue(cellValuePlayer1);
            cellPlayer2.setCellValue(cellValuePlayer2);
        }
        if (!resultsRandom.isEmpty()) {
            int file = 0;//hay que ir a buscar el randomfile
            Cell cellDraw = rowDraw.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC);
            Cell cellPlayer1 = rowPlayer1.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC);
            Cell cellPlayer2 = rowPlayer2.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC);
            cellDraw.setCellStyle(cellStyle);
            cellPlayer1.setCellStyle(cellStyle);
            cellPlayer2.setCellStyle(cellStyle);
            //                StatisticForCalc get = resultsRandom.get(randomPerceptronFile);
            //                Double cellValuePlayer1 = get.getWinRatePlayer1();
            Double cellValuePlayer1 = resultsRandom.get(randomPerceptronFile).getWinRatePlayer1();
            Double cellValuePlayer2 = resultsRandom.get(randomPerceptronFile).getWinRatePlayer2();
            Double cellValueDraw = resultsRandom.get(randomPerceptronFile).getDrawRate();
            //assert cellValueDraw + cellValuePlayer1 + cellValuePlayer2 == 100;

            cellPlayer1.setCellValue(cellValuePlayer1);
            cellPlayer2.setCellValue(cellValuePlayer2);
            cellDraw.setCellValue(cellValueDraw);
        }
        wb.write(outputXLSX);
    }
}

From source file:at.mukprojects.exclycore.dao.XLSXWriter.java

License:Open Source License

/**
 * This method lets you create the workbook. The workbook can be used to
 * create or edit Excel content. After finishing the writing process its
 * necessary to close the workbook with the the method called closeWorkbook.
 * //from   ww w .ja v  a  2s  .  com
 * @param output
 *            The output file.
 * @param add
 *            Set this parameter to tell the writer if you want to append
 *            the content to an existing file or if you want to create a
 *            completely new file.
 * @return Returns the workbook.
 * @throws IOException
 *             The Exception is thrown if an error occurs.
 */
protected XSSFWorkbook createWorkbook(File output, boolean add) throws IOException {
    log.info("Workbook gets created...");

    this.output = output;

    if (add) {
        log.info("The content will be appended to the existing file.");

        if (output.exists() && output.getName().endsWith("xlsx")) {
            try {
                outputWorkbook = (XSSFWorkbook) WorkbookFactory.create(output);
            } catch (InvalidFormatException e) {
                log.error("The Writer is unable to open" + " the existing Workbook.", e);
                throw new IOException("The Writer is unable to open" + " the existing Workbook.", e);
            }
            tempOutput = new File(output.getAbsolutePath() + ".temp");
            outputStream = new FileOutputStream(tempOutput);
        } else {
            outputStream = new FileOutputStream(output);
            outputWorkbook = new XSSFWorkbook();
        }
    } else {
        log.info("The content will be written in a new file.");

        outputStream = new FileOutputStream(output);
        outputWorkbook = new XSSFWorkbook();
    }

    return outputWorkbook;
}

From source file:b01.officeLink.excel.FocExcelDocument.java

License:Apache License

public FocExcelDocument(InputStream inputStream, ExcelRefillerInterface excelRefillerInterface)
        throws IOException {

    try {/*from   w w  w .  ja  v  a 2s.  c om*/
        workbook = WorkbookFactory.create(inputStream);
    } catch (InvalidFormatException e) {
        e.printStackTrace();
    }
    this.excelRefiller = excelRefillerInterface;
}

From source file:b01.officeLink.excel.synchronize.ExcelSyncFileReader.java

License:Apache License

private void openWorkbook(File file) {
    this.file = file;
    error = !file.getAbsolutePath().endsWith(OfficeLink.PREFIX_EXCEL_XP)
            && !file.getAbsolutePath().endsWith(OfficeLink.PREFIX_EXCEL_07);
    if (error) {/*  ww  w.ja  va  2s.  c  o  m*/
        Globals.logString("This is not an Excel extension file");
    }
    if (!error) {
        error = !file.exists();
        Globals.logString("File Does not Exist!");
    }
    if (!error) {
        inputStream = Globals.getInputStream(file.getAbsolutePath());
        try {
            workbook = WorkbookFactory.create(inputStream);
        } catch (IOException e) {
            Globals.logExceptionWithoutPopup(e);
            error = true;
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        error = error || workbook == null;
    }
}

From source file:bad.robot.excel.workbook.PoiWorkbookReader.java

License:Apache License

@Override
public Workbook read(InputStream stream) throws IOException {
    if (stream == null)
        throw new IllegalArgumentException("stream was null, could not load the workbook");
    try {/*ww w . jav  a2  s .  c om*/
        return WorkbookFactory.create(stream);
    } catch (InvalidFormatException e) {
        throw new IOException(e);
    } finally {
        stream.close();
    }
}

From source file:biz.webgate.domino.poi.demodb.poweraction.ImportAction.java

License:Apache License

@Override
protected Workbook doItPriv(Workbook arg0, HashMap<String, String> hsCurrent) throws Exception {
    System.out.println("Accessing -> " + hsCurrent.get("FILE"));
    File excelFile = new java.io.File(hsCurrent.get("FILE"));
    Workbook wb2 = WorkbookFactory.create(excelFile);
    System.out.println("###Got the file and first sheetName is -> " + wb2.getSheetName(0));
    return wb2;// w ww  .ja  va 2s  .  co  m
}

From source file:biz.webgate.dominoext.poi.component.kernel.WorkbookProcessor.java

License:Apache License

public Workbook processWorkbook(ITemplateSource itsCurrent, List<Spreadsheet> lstSP, FacesContext context,
        UIWorkbook uiWB) throws IOException, InvalidFormatException, POIException {
    Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());

    InputStream is = itsCurrent.getFileStream();
    // Workbook wbCurrent = WorkbookFactory.create(is);
    // ;//from w ww.  j  av a 2 s .  c o  m
    Workbook wbCurrent1 = WorkbookFactory.create(is);
    Workbook wbCurrent = wbCurrent1;
    is.close();
    if (wbCurrent1 instanceof XSSFWorkbook && uiWB.isUseStreamingModel()) {
        logCurrent.info("Generation SXSSFWorkbook");
        wbCurrent = new SXSSFWorkbook((XSSFWorkbook) wbCurrent1);
    }
    itsCurrent.cleanUP();
    // Processing all Spreadsheets to the File
    logCurrent.finer("Push the Result to the HttpServlet");

    for (Spreadsheet spCurrent : lstSP) {
        processSpreadSheet(spCurrent, wbCurrent, context);
    }
    if (uiWB != null) {
        logCurrent.finer("Post Generation Process");
        uiWB.postGenerationProcess(context, wbCurrent);
    }
    return wbCurrent;
}

From source file:biz.webgate.dominoext.poi.util.POILibUtil.java

License:Apache License

public static Workbook getWorkbook(InputStream inExcel) {
    Workbook wbRC = null;/* www.  j  a  va2s  .  co  m*/
    try {
        wbRC = WorkbookFactory.create(inExcel);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return wbRC;
}

From source file:blanco.commons.calc.parser.AbstractBlancoCalcParser.java

License:Open Source License

/**
 * ???/*from   ww  w.j  a  va 2 s  . co  m*/
 * 
 * @param inputSource
 *            ???
 * @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource)
 */
public final void parse(final InputSource inputSource) throws IOException, SAXException {

    System.out.println("AbstractBlancoCalcParser#:parse");

    Workbook workbook = null;

    InputStream inStream = null;
    try {
        if (inputSource.getByteStream() != null) {
            // OK??????????
        } else if (inputSource.getSystemId() != null && inputSource.getSystemId().length() > 0) {
            inStream = new FileInputStream(inputSource.getSystemId());
            inputSource.setByteStream(inStream);
        } else {
            throw new IOException("??InputSource???????.");
        }
        workbook = WorkbookFactory.create(inputSource.getByteStream());

        // ????????
        parseWorkbook(workbook);
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("???????.: " + e.toString());
    } catch (InvalidFormatException e) {
        e.printStackTrace();
        throw new IOException("???????.: " + e.toString());
    } finally {
        if (workbook != null) {
            workbook.close();
        }

        // InputSource??????
        // ???? ?????????
        if (inStream != null) {
            inStream.close();
        }
    }
}