Example usage for org.apache.poi.openxml4j.opc OPCPackage close

List of usage examples for org.apache.poi.openxml4j.opc OPCPackage close

Introduction

In this page you can find the example usage for org.apache.poi.openxml4j.opc OPCPackage close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Close the open, writable package and save its content.

Usage

From source file:excel.FromHowTo.java

License:Apache License

public void processAllSheets(String filename) throws Exception {
    OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
    try {/*from w ww .  j av  a  2s .c  o  m*/
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();

        XMLReader parser = fetchSheetParser(sst);

        Iterator<InputStream> sheets = r.getSheetsData();
        while (sheets.hasNext()) {
            System.out.println("Processing new sheet:\n");
            InputStream sheet = sheets.next();
            InputSource sheetSource = new InputSource(sheet);
            parser.parse(sheetSource);
            sheet.close();
            System.out.println("");
        }
    } finally {
        pkg.close();
    }
}

From source file:GapAnalysis.gapAnalysis.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //PrintWriter out = response.getWriter();
    try {// www .  j  a v a  2s .c om

        ArrayList keyal = new ArrayList();
        ArrayList countyal = new ArrayList();
        ArrayList scountyal = new ArrayList();
        ArrayList facilal = new ArrayList();
        ArrayList yearmonthal = new ArrayList();
        ArrayList monthal = new ArrayList();
        ArrayList sectional = new ArrayList();

        XSSFWorkbook wb;

        String periodname = "";
        String allpath = getServletContext().getRealPath("/Gapanalysis.xlsm");

        System.out.println(allpath);

        XSSFWorkbook workbook;
        String mydrive = allpath.substring(0, 1);
        // wb = new XSSFWorkbook( OPCPackage.open(allpath) );

        Date da = new Date();
        String dat2 = da.toString().replace(" ", "_");
        dat2 = dat2.toString().replace(":", "_");

        String np = mydrive + ":\\APHIAPLUS\\InternalSystem\\Gapanalysis" + dat2 + ".xlsm";
        System.out.println("path:: " + np);
        // String desteepath1 = getServletContext().getRealPath("/Females 15to24.xlsm");
        String sr = getServletContext().getRealPath("/Gapanalysis.xlsm");
        //check if file exists

        //first time , it should create those folders that host the macro file
        File f = new File(np);
        if (!f.exists() && !f.isDirectory()) { /* do something */
            copytemplates ct = new copytemplates();
            ct.transfermacros(sr, np);
            //rem np is the destination file name  

            System.out.println("Copying macro template first time ..");

        } else
        //copy the file alone  
        {
            copytemplates ct = new copytemplates();
            //copy the agebased file only
            ct.copymacros(sr, np);

        }
        String filepth = np;

        File allpathfile = new File(filepth);

        OPCPackage pkg = OPCPackage.open(allpathfile);

        pathtodelete = filepth;
        wb = new XSSFWorkbook(pkg);

        dbConn conn = new dbConn();
        HashMap<String, String> rawdatahashmap = new HashMap<String, String>();

        int year = 0;
        String yearval = "";
        int prevyear = 0;

        String quarter = "";

        String yearmonth = "";
        String startyearmonth = "";
        String endyearmonth = "";

        yearval = request.getParameter("year").toString();

        System.out.println("YEARVAL" + yearval);
        year = Integer.parseInt(yearval);
        prevyear = year - 1;
        quarter = request.getParameter("quarter");
        periodname += yearval + "_";
        if (quarter.equals("1")) {
            startyearmonth = prevyear + "10";
            endyearmonth = prevyear + "12";
            periodname = prevyear + "_(Oct_Dec)";
        } else if (quarter.equals("2")) {
            startyearmonth = year + "01";
            endyearmonth = year + "03";
            periodname = yearval + "_(Jan-Mar)";
        } else if (quarter.equals("3")) {
            startyearmonth = year + "04";
            endyearmonth = year + "06";
            periodname = yearval + "_(Apr_Jun)";
        } else if (quarter.equals("4")) {
            startyearmonth = year + "07";
            endyearmonth = year + "09";
            periodname = yearval + "_(Jul_Sep)";
        }

        int colsmerging = 6;
        String Sections[] = { "ART", "HTC", "PMTCT" };
        String headers[] = { "County", "Sub-County", "Facility", "Year", "Month" };
        String headergsn[] = { "County", "Sub-County", "Facility" };
        //if one wants gaps for one service area
        if (request.getParameterValues("gapsection") != null) {

            Sections = request.getParameterValues("gapsection");

        }
        //This is the loop that well use to create worksheets for each 

        String period = " 1=1 and Annee=" + yearval + " and yearmonth between " + startyearmonth + " and "
                + endyearmonth + " ";
        String gsnperiod = " 1=1  ";

        //______________________________________________________________________________________
        //______________________________________________________________________________________

        Font font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        CellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        CellStyle stylex1 = wb.createCellStyle();
        stylex1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex1.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        CellStyle stylex2 = wb.createCellStyle();
        stylex2.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        stylex2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex2.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        CellStyle stylex3 = wb.createCellStyle();
        stylex3.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        stylex3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex3.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex3.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex3.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex3.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex3.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        Font fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);
        stylex1.setFont(fontx);
        stylex1.setWrapText(true);

        stylex2.setFont(fontx);
        stylex2.setWrapText(true);

        //==================================================

        for (int a = 0; a < Sections.length; a++) {
            int column = 0;
            int Row = 3;

            Sheet shet = wb.createSheet(Sections[a]);

            Row rwx = shet.createRow(2);
            Row rw1 = null;
            Row rw2 = null;
            Row rw = shet.createRow(0);
            rw.setHeightInPoints(25);
            Cell cl0 = rw.createCell(0);
            cl0.setCellValue(Sections[a] + " GAP ANALYSIS");
            cl0.setCellStyle(stylex1);

            //this will depend on the length of the number of elements being checked

            for (int b = 1; b <= colsmerging; b++) {
                Cell clx = rw.createCell(b);
                clx.setCellValue("");
                clx.setCellStyle(stylex);
            }

            //now go to the database and do a query for each section
            int determinant = 2;
            String getqueries = " Select * from gap_analysis where active=1 and section='" + Sections[a] + "' ";

            conn.rs = conn.st.executeQuery(getqueries);
            while (conn.rs.next()) {

                //if an excel sheet exists, then get the row number 1

                if (shet.getRow(1) != null) {
                    rw1 = shet.getRow(1);
                } else {
                    rw1 = shet.createRow(1);
                    rw1.setHeightInPoints(25);
                }

                //print blanks before printing real header
                //for gsns, we only print three columns and no period
                if (conn.rs.getString("id").equals("1")) {

                    for (int p = 0; p < headergsn.length; p++) {
                        Cell cl2 = rw1.createCell(column + p);
                        cl2.setCellValue("");
                        cl2.setCellStyle(stylex);
                        shet.setColumnWidth(column + p, 5000);
                    }
                } else {

                    for (int p = 0; p < headers.length; p++) {
                        Cell cl2 = rw1.createCell(column + p);
                        cl2.setCellValue("");
                        cl2.setCellStyle(stylex);
                        shet.setColumnWidth(column + p, 5000);
                    }

                }
                determinant++;
                if (determinant % 2 == 0) {

                    Cell cl1 = rw1.createCell(column);
                    cl1.setCellValue(conn.rs.getString("rule"));
                    cl1.setCellStyle(stylex3);

                } else {

                    Cell cl1 = rw1.createCell(column);
                    cl1.setCellValue(conn.rs.getString("rule"));
                    cl1.setCellStyle(stylex2);

                }

                //Create the column header  

                if (shet.getRow(2) != null) {
                    rw2 = shet.getRow(2);
                } else {
                    rw2 = shet.createRow(2);
                    rw2.setHeightInPoints(25);
                }
                if (conn.rs.getString("id").equals("1")) {

                    for (int p = 0; p < headergsn.length; p++) {
                        Cell cl2 = rw2.createCell(column + p);
                        cl2.setCellValue(headergsn[p]);
                        cl2.setCellStyle(stylex);
                    }
                } else {

                    for (int p = 0; p < headers.length; p++) {
                        Cell cl2 = rw2.createCell(column + p);
                        cl2.setCellValue(headers[p]);
                        cl2.setCellStyle(stylex);
                    }

                }

                String currentqry = conn.rs.getString("query");
                //process each query as you 
                //pass the necessary period parameters from the interface
                //rem each query ends with a 'and'
                if (conn.rs.getString("id").equals("1")) {
                    currentqry += gsnperiod;
                } else {

                    currentqry += period + " and subpartnera." + Sections[a] + "= 1 ";

                }

                System.out.println("" + currentqry);
                Row = 3;
                conn.rs1 = conn.st1.executeQuery(currentqry);

                while (conn.rs1.next()) {

                    if (shet.getRow(Row) != null) {
                        rwx = shet.getRow(Row);
                    } else {
                        rwx = shet.createRow(Row);
                        rwx.setHeightInPoints(25);
                    }
                    Cell cly = rwx.createCell(column);
                    cly.setCellValue(conn.rs1.getString("County"));
                    cly.setCellStyle(style2);

                    Cell cly2 = rwx.createCell(column + 1);
                    cly2.setCellValue(conn.rs1.getString("DistrictNom"));
                    cly2.setCellStyle(style2);//gsn sites do not have a yearmonth

                    Cell cly1 = rwx.createCell(column + 2);
                    cly1.setCellValue(conn.rs1.getString("SubPartnerNom"));
                    cly1.setCellStyle(style2);

                    //if the current list is not inclusive of GSNs

                    if (!conn.rs.getString(1).equals("1")) {

                        Cell cly3 = rwx.createCell(column + 3);
                        cly3.setCellValue(new Integer(conn.rs1.getString("yearmonth").substring(0, 4)));
                        cly3.setCellStyle(style2);

                        //the month section

                        Cell cly3x = rwx.createCell(column + 4);
                        cly3x.setCellValue(new Integer(conn.rs1.getString("yearmonth").substring(4)));
                        cly3x.setCellStyle(style2);

                        //my key is a 
                        String mykey = Sections[a] + conn.rs1.getString("SubPartnerNom") + "_"
                                + conn.rs1.getString("yearmonth") + "_";
                        //add all the facilities at this point
                        //ignore the sites in ART since they are static
                        if (!keyal.contains(mykey)) {
                            keyal.add(mykey);
                            countyal.add(conn.rs1.getString("County"));
                            scountyal.add(conn.rs1.getString("DistrictNom"));
                            facilal.add(conn.rs1.getString("SubPartnerNom"));
                            sectional.add(Sections[a]);
                            yearmonthal.add(conn.rs1.getString("yearmonth"));
                            monthal.add(conn.rs1.getString("yearmonth").substring(4));

                        }

                    }

                    Row++;

                }

                if (conn.rs.getString(1).equals("1")) {
                    column += 3;
                } else {
                    column += 5;
                }
                if (conn.rs.getString("id").equals("1")) {
                    shet.addMergedRegion(new CellRangeAddress(1, 1, 0, column - 1));
                } else {
                    shet.addMergedRegion(new CellRangeAddress(1, 1, column - 5, column - 1));
                }

            } //end of all queries per section

            shet.addMergedRegion(new CellRangeAddress(0, 0, 0, column - 1));

        } // end of sheets loop   

        //create a new sheet

        //county   subcounty   facility   yearmonth   section

        Sheet shet = wb.getSheet("Sheet1");

        Row rw = shet.createRow(0);
        Cell cl0 = rw.createCell(0);
        cl0.setCellValue("county");
        cl0.setCellStyle(stylex1);

        Cell cl1 = rw.createCell(1);
        cl1.setCellValue("subcounty");
        cl1.setCellStyle(stylex1);

        Cell cl2 = rw.createCell(2);
        cl2.setCellValue("facility");
        cl2.setCellStyle(stylex1);

        Cell cl3 = rw.createCell(3);
        cl3.setCellValue("year");
        cl3.setCellStyle(stylex1);

        Cell cl4 = rw.createCell(4);
        cl4.setCellValue("month");
        cl4.setCellStyle(stylex1);

        Cell cl5 = rw.createCell(5);
        cl5.setCellValue("section");
        cl5.setCellStyle(stylex1);

        for (int q = 0; q < keyal.size(); q++) {

            Row rwx = shet.createRow(q + 1);

            Cell cl01 = rwx.createCell(0);
            cl01.setCellValue(countyal.get(q).toString());
            cl01.setCellStyle(style2);

            Cell cl11 = rwx.createCell(1);
            cl11.setCellValue(scountyal.get(q).toString());
            cl11.setCellStyle(style2);

            Cell cl21 = rwx.createCell(2);
            cl21.setCellValue(facilal.get(q).toString());
            cl21.setCellStyle(style2);

            Cell cl31 = rwx.createCell(3);
            cl31.setCellValue(new Integer(yearmonthal.get(q).toString().substring(0, 4)));
            cl31.setCellStyle(style2);

            Cell cl41 = rwx.createCell(4);
            cl41.setCellValue(new Integer(monthal.get(q).toString()));
            cl41.setCellStyle(style2);

            Cell cl51 = rwx.createCell(5);
            cl51.setCellValue(sectional.get(q).toString());
            cl51.setCellStyle(style2);

        }

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition",
                "attachment; filename=GapAnalysis_For" + periodname + "_Generatted_On_" + createdOn + ".xlsm");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
        outStream.close();
        pkg.close();

        if (conn.rs != null) {
            conn.rs.close();
        }
        if (conn.rs1 != null) {
            conn.rs1.close();
        }
        if (conn.st1 != null) {
            conn.st1.close();
        }
        if (conn.st != null) {
            conn.st.close();
        }

        File file = new File(pathtodelete);
        System.out.println("path: 2" + pathtodelete);

        if (file.delete()) {
            System.out.println(file.getName() + " is deleted!");
        } else {
            System.out.println("Delete operation  failed.");
        }

    } catch (SQLException ex) {
        Logger.getLogger(gapAnalysis.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(gapAnalysis.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

    }
}

From source file:gov.nih.nci.evs.app.neopl.XLSXMetadataUtils.java

License:Open Source License

public static String getCreator(File file) {
    String author = null;/* w  ww.  j  a  v  a2  s  .c o m*/
    try {
        OPCPackage pkg = OPCPackage.open(file);
        POIXMLProperties props = new POIXMLProperties(pkg);
        POIXMLProperties.CoreProperties core_properties = props.getCoreProperties();
        author = core_properties.getCreator();
        pkg.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return author;
}

From source file:gov.nih.nci.evs.app.neopl.XLSXMetadataUtils.java

License:Open Source License

public static void setCreator(File file, String author) {
    try {/*from  ww w  . ja  v a  2s  .co m*/
        OPCPackage pkg = OPCPackage.open(file);
        POIXMLProperties props = new POIXMLProperties(pkg);
        POIXMLProperties.CoreProperties core_properties = props.getCoreProperties();
        core_properties.setCreator(author);
        pkg.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:gov.nih.nci.evs.app.neopl.XLSXMetadataUtils.java

License:Open Source License

public static String getPOISummaryData(String filename, String key) {
    String value = null;//from w w w .j a  v  a 2s.c o m
    OPCPackage pkg = null;
    try {
        pkg = OPCPackage.open(new File(filename));
        POIXMLProperties props = new POIXMLProperties(pkg);
        POIXMLProperties.CoreProperties core_properties = props.getCoreProperties();

        if (key.compareTo(SUMMARY_DATA_AUTHOR) == 0) {
            value = core_properties.getCreator();
        } else if (key.compareTo(SUMMARY_DATA_KEYWORDS) == 0) {
            value = core_properties.getKeywords();
        } else if (key.compareTo(SUMMARY_DATA_TITLE) == 0) {
            value = core_properties.getTitle();
        } else if (key.compareTo(SUMMARY_DATA_SUBJECT) == 0) {
            value = core_properties.getSubject();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            pkg.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    return value;
}

From source file:gov.nih.nci.evs.app.neopl.XLSXMetadataUtils.java

License:Open Source License

public static void setPOISummaryData(String filename, String key, String value) {
    OPCPackage pkg = null;
    try {//from   w w  w .  j  ava2  s.c o m
        pkg = OPCPackage.open(new File(filename));
        POIXMLProperties props = new POIXMLProperties(pkg);
        POIXMLProperties.CoreProperties core_properties = props.getCoreProperties();

        if (key.compareTo(SUMMARY_DATA_AUTHOR) == 0) {
            core_properties.setCreator(value);
        } else if (key.compareTo(SUMMARY_DATA_KEYWORDS) == 0) {
            core_properties.setKeywords(value);
        } else if (key.compareTo(SUMMARY_DATA_TITLE) == 0) {
            core_properties.setTitle(value);
        } else if (key.compareTo(SUMMARY_DATA_SUBJECT) == 0) {
            core_properties.setSubjectProperty(value);
        }

    } catch (Exception ex) {
        //ex.printStackTrace();
    } finally {
        try {
            pkg.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:gov.nih.nci.evs.app.neopl.XLSXMetadataUtils.java

License:Open Source License

public static void setPOISummaryData(String filename, String[] keys, String[] values) {
    OPCPackage pkg = null;
    try {//from   w  w  w . jav a 2 s  .  com
        pkg = OPCPackage.open(new File(filename));
        POIXMLProperties props = new POIXMLProperties(pkg);
        POIXMLProperties.CoreProperties core_properties = props.getCoreProperties();

        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            String value = values[i];
            if (key.compareTo(SUMMARY_DATA_AUTHOR) == 0) {
                core_properties.setCreator(value);
            } else if (key.compareTo(SUMMARY_DATA_KEYWORDS) == 0) {
                core_properties.setKeywords(value);
            } else if (key.compareTo(SUMMARY_DATA_TITLE) == 0) {
                core_properties.setTitle(value);
            } else if (key.compareTo(SUMMARY_DATA_SUBJECT) == 0) {
                core_properties.setSubjectProperty(value);
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            pkg.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:hsio.snippet.java.poi.examples.XLSX2CSV.java

License:Apache License

public static void main(String[] args) throws Exception {
    File xlsxFile = new File("./samples/excel/big-number.xlsx");

    int minColumns = -1;
    if (args.length >= 2)
        minColumns = Integer.parseInt(args[1]);

    // The package open is instantaneous, as it should be.
    OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ);
    XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns);
    xlsx2csv.process();/*from  ww w  .j  a  v  a 2  s  .  co m*/
    p.close();
}

From source file:org.alfresco.repo.content.transform.OOXMLThumbnailContentTransformer.java

License:Open Source License

@Override
protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws Exception {
    final String sourceMimetype = reader.getMimetype();
    final String sourceExtension = getMimetypeService().getExtension(sourceMimetype);
    final String targetMimetype = writer.getMimetype();

    if (log.isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("Transforming from ").append(sourceMimetype).append(" to ").append(targetMimetype);
        log.debug(msg.toString());/*from   www  .  j a v a 2 s .  c o  m*/
    }

    OPCPackage pkg = null;
    try {
        File ooxmlTempFile = TempFileProvider.createTempFile(this.getClass().getSimpleName() + "_ooxml",
                sourceExtension);
        reader.getContent(ooxmlTempFile);

        // Load the file
        pkg = OPCPackage.open(ooxmlTempFile.getPath());

        // Does it have a thumbnail?
        PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL);
        if (rels.size() > 0) {
            // Get the thumbnail part
            PackageRelationship tRel = rels.getRelationship(0);
            PackagePart tPart = pkg.getPart(tRel);

            // Write it to the target
            InputStream tStream = tPart.getInputStream();
            writer.putContent(tStream);
            tStream.close();
        } else {
            log.debug("No thumbnail present in " + reader.toString());
            throw new UnimportantTransformException(NO_THUMBNAIL_PRESENT_IN_FILE + targetMimetype);
        }
    } catch (IOException e) {
        throw new AlfrescoRuntimeException("Unable to transform " + sourceExtension + " file.", e);
    } finally {
        if (pkg != null) {
            pkg.close();
        }
    }
}

From source file:org.nekorp.workflow.desktop.control.imp.ProgramacionServicioWizardImp.java

License:Apache License

@Override
public void importarArchivo(File archivo) {
    programacionMetadata.setDetalles("");
    OPCPackage pkg = null;
    try {/*www.ja  v a  2  s  . com*/
        addDetail("Leyendo archivo: " + archivo.getCanonicalPath());
        pkg = OPCPackage.open(archivo);
        XSSFWorkbook wb = new XSSFWorkbook(pkg);
        //Workbook wb = WorkbookFactory.create(archivo);
        Sheet sheet = wb.getSheetAt(0);
        //Row encabezado = sheet.getRow(0);
        List<String> nombresServicios = null;
        boolean inicio = true;
        nuevosAutos = new LinkedList<>();
        nuevosServicio = new LinkedList<>();
        for (Row row : sheet) {
            if (inicio) {
                nombresServicios = procesarEncabezado(row);
                inicio = false;
            } else {
                if (row.getPhysicalNumberOfCells() == nombresServicios.size()) {
                    Auto autoCargado = new Auto();
                    cargarDatosAuto(row, autoCargado);
                    autoBridge.load(autoCargado, servicio.getAuto());
                    Servicio nuevoServicio = new Servicio();
                    if (buscarNuevoServicio(row, nuevoServicio, nombresServicios, rangoNuevo)) {
                        //se intentan cargar
                        servicioBridge.load(nuevoServicio, servicio);
                        addDetail("Se encontro un nuevo servicio para el auto con numero de serie: "
                                + autoCargado.getNumeroSerie());
                        addDetail("Descripcin del servicio encontrado:\n" + nuevoServicio.getDescripcion());
                        if (validacionGeneralDatosAuto.isValido()) {
                            nuevosAutos.add(autoCargado);
                            nuevosServicio.add(nuevoServicio);
                        } else {
                            addDetail(
                                    "los datos del nuevo servicio tienen los siguientes errores y no se dara de alta:");
                            addDetail(validacionDatosAuto.concatenaErrores());
                        }
                    }
                    List<AlertaServicio> nuevasAlertas = buscarAlertas(row, nombresServicios, rangoAlerta);
                    for (AlertaServicio x : nuevasAlertas) {
                        x.setMarcaAuto(autoCargado.getMarca());
                        x.setPlacasAuto(autoCargado.getPlacas());
                        x.setTipoAuto(autoCargado.getTipo());
                        x.setNombreCliente(servicio.getCliente().getNombre());
                        addDetail("Se encontro un servicio proximo para el auto con numero de serie: "
                                + autoCargado.getNumeroSerie());
                        addDetail("Descripcin de la nueva alerta:\n" + x.getDescripcionServicio());
                        alertas.add(x);
                    }
                    AlertaVerificacion nuevaAlerta = buscarAlertasVerificacion(autoCargado.getPlacas());
                    if (nuevaAlerta != null) {
                        addDetail("Se encontro un auto que pudiera necesitar verificacin: "
                                + autoCargado.getNumeroSerie());
                        addDetail(
                                "placas: " + nuevaAlerta.getPlacas() + " periodo: " + nuevaAlerta.getPeriodo());
                        alertasVerificacion.add(nuevaAlerta);
                    }
                }
            }
        }
        if (nuevosServicio.size() > 0) {
            if (nuevosServicio.size() == 1) {
                addDetail("Se tiene listo para crear un nuevo servicio");
            } else {
                addDetail("Se tienen listos para crear " + nuevosServicio.size() + " servicios nuevos");
            }
        } else {
            addDetail("No se encontro ningun nuevo servicio");
        }
        int cantidadAlertas = alertas.size() + alertasVerificacion.size();
        if (cantidadAlertas > 0) {
            if (cantidadAlertas == 1) {
                addDetail("Se tiene lista para enviar una nueva alerta");
            } else {
                addDetail("Se tienen listas para enviar " + cantidadAlertas + " alertas");
            }
        } else {
            addDetail("No se encontro ninguna alerta");
        }
        if (nuevosServicio.size() > 0 || cantidadAlertas > 0) {
            validacionGeneralProgramacion.setValido(true);
        } else {
            validacionGeneralProgramacion.setValido(false);
        }
    } catch (IOException | InvalidFormatException | IllegalArgumentException ex) {
        ProgramacionServicioWizardImp.LOGGER.error("exploto!!!", ex);
        addDetail("ocurrio un error inesperado al leer el archivo." + ex.getMessage());
    } finally {
        if (pkg != null) {
            try {
                pkg.close();
            } catch (IOException ex) {
                //ProgramacionServicioWizardImp.LOGGER.error("exploto!!!", ex);
            }
        }
    }
}