Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook close

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook close

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFWorkbook close.

Prototype

@Override
    public void close() throws IOException 

Source Link

Usage

From source file:it.vige.greenarea.file.ImportaXLSFile.java

License:Apache License

@Override
public List<RichiestaXML> prelevaDati(InputStream inputStream, List<Filtro> filtri) throws Exception {
    if (filtri != null)
        acceptedRoundCodes.addAll(filtri);
    XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
    Sheet sheet = workbook.getSheetAt(0);

    int rowsCount = sheet.getPhysicalNumberOfRows();
    List<RichiestaXML> richiesteXML = new ArrayList<RichiestaXML>();
    for (int i = 1; i < rowsCount; i++) {
        Row row = sheet.getRow(i);/*from w  ww. j  a  v  a2s. c om*/
        int colCounts = row.getLastCellNum();
        RichiestaXML richiestaXML = new RichiestaXML();
        for (int j = 0; j < colCounts; j++) {
            Cell cell = row.getCell(j);
            if (cell != null)
                aggiungiCampoARichiestaXML(richiestaXML, cell, j);
        }
        String roundCode = richiestaXML.getRoundCode();
        if (acceptRoundCode(roundCode))
            richiesteXML.add(richiestaXML);
    }
    workbook.close();
    return richiesteXML;
}

From source file:jpgtoxlsx.JPGtoXLSX.java

/**
 * @param args the command line arguments
 *//*from   www  .ja v a 2  s  . co m*/
public static void main(String[] args) throws Exception {

    XSSFWorkbook myExcel = new XSSFWorkbook();
    XSSFSheet sheet = myExcel.createSheet("Image");

    BufferedImage image = null;

    int width, height;
    int xlrows;
    //int pixel;

    File fimg;
    //open image
    try {
        fimg = new File("C:\\excel\\Test.jpg");
        image = ImageIO.read(fimg);
    } catch (IOException e) {
        System.out.println(e);
    }

    width = image.getWidth();
    //System.out.println(width);
    height = image.getHeight();
    //System.out.println(height);

    xlrows = height * 3;

    //System.out.println(pixel);

    int r, g, b;

    int w = image.getWidth();
    int h = image.getHeight();
    System.out.println("Width: " + w + "Height: " + h);
    System.out.println("Generating RGB values..");

    XSSFCellStyle style1 = myExcel.createCellStyle();
    XSSFCellStyle style2 = myExcel.createCellStyle();
    XSSFCellStyle style3 = myExcel.createCellStyle();

    for (int i = 1; i < ++h; i++) {

        if (i == image.getHeight()) {
            break;
        }

        XSSFRow row1 = sheet.createRow((i * 3 - 3));
        XSSFRow row2 = sheet.createRow((i * 3 - 2));
        XSSFRow row3 = sheet.createRow((i * 3 - 1));

        for (int j = 0; j < ++w; j++) {

            if (j == image.getWidth()) {
                break;
            }

            //System.out.println("I: " + i);
            //System.out.println("J: " + j + "\n");
            int x = i;
            int y = j;

            //System.out.println("X: " + x + "Y: " + y + "\r");
            //System.out.println("Y: " + y);
            int pixel = image.getRGB(y, x);
            r = (pixel >> 16) & 0xff;
            g = (pixel >> 8) & 0xff;
            b = (pixel) & 0xff;

            XSSFCell cell1 = row1.createCell(y);
            XSSFCell cell2 = row2.createCell(y);
            XSSFCell cell3 = row3.createCell(y);

            cell1.setCellValue(Integer.toString(r));
            cell2.setCellValue(Integer.toString(g));
            cell3.setCellValue(Integer.toString(b));

            style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(r, 0, 0)));
            ;
            style1.setFillPattern(CellStyle.SOLID_FOREGROUND);

            style2.setFillForegroundColor(new XSSFColor(new java.awt.Color(0, g, 0)));
            style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

            style3.setFillForegroundColor(new XSSFColor(new java.awt.Color(0, 0, b)));
            style3.setFillPattern(CellStyle.SOLID_FOREGROUND);

            cell1.setCellStyle(style1);
            cell2.setCellStyle(style2);
            cell3.setCellStyle(style3);

            //System.out.println("x,y: " + j + ", " + i);
            //System.out.println("R: " + r + " G: " + g + " B: " + b + "\n");
        }
    }
    System.out.println("RGB values extracted.");
    System.out.println("Generating image");

    myExcel.write(new FileOutputStream("excel.xlsx"));
    myExcel.close();

}

From source file:mil.tatrc.physiology.datamodel.dataset.DataSetReader.java

License:Apache License

public static void loadData(String directoryName, String fileName) {
    try {//  ww  w  . j  a  v  a  2 s . c o  m
        // Delete current dir contents
        FileUtils.delete(new File("./substances/"));
        FileUtils.delete(new File("./patients/"));
        FileUtils.delete(new File("./environments/"));
        FileUtils.delete(new File("./nutrition/"));
        FileUtils.delete(new File("./config/"));
        // Ok, let's make them again
        FileUtils.createDirectory("./substances/");
        FileUtils.createDirectory("./patients/");
        FileUtils.createDirectory("./environments/");
        FileUtils.createDirectory("./nutrition/");
        FileUtils.createDirectory("./config/");
    } catch (Exception ex) {
        Log.error("Unable to clean directories");
        return;
    }
    try {
        File xls = new File(directoryName + "/" + fileName);
        if (!xls.exists()) {
            Log.error("Could not find xls file " + directoryName + "/" + fileName);
            return;
        }
        FileInputStream xlFile = new FileInputStream(directoryName + "/" + fileName);
        XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
        evaluator = xlWBook.getCreationHelper().createFormulaEvaluator();

        List<SEPatient> patients = readPatients(xlWBook.getSheet("Patients"));
        for (SEPatient p : patients) {
            Log.info("Writing patient : " + p.getName());
            CDMSerializer.writeFile("./patients/" + p.getName() + ".xml", p.unload());
        }
        Map<String, SESubstance> substances = readSubstances(xlWBook.getSheet("Substances"));
        for (SESubstance s : substances.values()) {
            Log.info("Writing substance : " + s.getName());
            CDMSerializer.writeFile("./substances/" + s.getName() + ".xml", s.unload());
        }
        List<SESubstanceCompound> compounds = readCompounds(xlWBook.getSheet("Compounds"), substances);
        for (SESubstanceCompound c : compounds) {
            Log.info("Writing compound : " + c.getName());
            CDMSerializer.writeFile("./substances/" + c.getName() + ".xml", c.unload());
        }
        Map<String, SEEnvironmentalConditions> environments = readEnvironments(xlWBook.getSheet("Environment"),
                substances);
        for (String name : environments.keySet()) {
            Log.info("Writing environment : " + name);
            environments.get(name).trim();//Removes zero amount ambient substances
            CDMSerializer.writeFile("./environments/" + name + ".xml", environments.get(name).unload());
        }
        Map<String, SENutrition> meals = readNutrition(xlWBook.getSheet("Nutrition"));
        for (String name : meals.keySet()) {
            Log.info("Writing nutrition : " + name);
            CDMSerializer.writeFile("./nutrition/" + name + ".xml", meals.get(name).unload());
        }
        Map<String, PhysiologyEngineStabilization> stabilization = readStabilization(
                xlWBook.getSheet("Stabilization"));
        for (String name : stabilization.keySet()) {
            Log.info("Writing stabilization : " + name);
            CDMSerializer.writeFile("./config/" + name + ".xml", stabilization.get(name).unload());
        }
        xlWBook.close();
    } catch (Exception ex) {
        Log.error("Error reading XSSF : " + directoryName + "/" + fileName, ex);
        return;
    }
}

From source file:mil.tatrc.physiology.utilities.Excel2PDF.java

License:Apache License

public static void convert(String from, String to) throws IOException {
    FileInputStream xlFile = new FileInputStream(new File(from));
    // Read workbook into HSSFWorkbook
    XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
    //We will create output PDF document objects at this point
    PDDocument pdf = new PDDocument();

    //pdf.addTitle();
    for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) {
        XSSFSheet xlSheet = xlWBook.getSheetAt(s);
        Log.info("Processing Sheet : " + xlSheet.getSheetName());
        PDPage page = new PDPage(PDRectangle.A4);
        page.setRotation(90);/*from  w  w w .  j  av  a2 s  .c  o m*/
        pdf.addPage(page);
        PDRectangle pageSize = page.getMediaBox();
        PDPageContentStream contents = new PDPageContentStream(pdf, page);
        contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference
        contents.setFont(PDType1Font.HELVETICA_BOLD, 16);
        contents.beginText();
        contents.newLineAtOffset(50, pageSize.getWidth() - 50);
        contents.showText(xlSheet.getSheetName());
        contents.endText();
        contents.close();

        int rows = xlSheet.getPhysicalNumberOfRows();
        for (int r = 0; r < rows; r++) {
            XSSFRow row = xlSheet.getRow(r);
            if (row == null)
                continue;
            int cells = row.getPhysicalNumberOfCells();
            if (cells == 0)
                continue;// Add an empty Roe

        }
    }

    /*    
        //We will use the object below to dynamically add new data to the table
        PdfPCell table_cell;
        //Loop through rows.
        while(rowIterator.hasNext()) 
        {
          Row row = rowIterator.next(); 
          Iterator<Cell> cellIterator = row.cellIterator();
          while(cellIterator.hasNext()) 
          {
            Cell cell = cellIterator.next(); //Fetch CELL
            switch(cell.getCellType()) 
            { //Identify CELL type
              //you need to add more code here based on
              //your requirement / transformations
              case Cell.CELL_TYPE_STRING:
    //Push the data from Excel to PDF Cell
    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
    //feel free to move the code below to suit to your needs
    my_table.addCell(table_cell);
    break;
            }
            //next line
          }
        }
    */
    pdf.save(new File(to));
    pdf.close();
    xlWBook.close();
    xlFile.close(); //close xls
}

From source file:mil.tatrc.physiology.utilities.testing.validation.ValdiationTool.java

License:Apache License

public void loadData(String revision, String env, String arch, boolean sendEmail) {
    String directoryName = DEFAULT_DIRECTORY;
    String fileName = DEFAULT_FILE;
    String destinationDirectory = DEST_DIRECTORY;
    try {//from   www .  j a v a2s.  co  m
        File dest = new File(DEST_DIRECTORY);
        dest.mkdir();
        // Delete current dir contents
        // FileUtils.delete(destinationDirectory);
        // Ok, let's make them again
        // FileUtils.createDirectory(destinationDirectory);
    } catch (Exception ex) {
        Log.error("Unable to clean directories");
        return;
    }
    try {
        File xls = new File(directoryName + "/" + fileName);
        if (!xls.exists()) {
            Log.error("Could not find xls file " + directoryName + "/" + fileName);
            return;
        }
        // Read in props file
        File file = new File("ValidationTables.config");
        FileInputStream fileInput = new FileInputStream(file);
        Properties config = new Properties();
        config.load(fileInput);
        fileInput.close();

        // Set up the Email object
        String hostname = "Unknown";
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostname = addr.getHostName();
        } catch (Exception ex) {
            System.out.println("Hostname can not be resolved");
        }
        EmailUtil email = new EmailUtil();
        String subj = env + " " + arch + " " + TABLE_TYPE + " Validation from " + hostname + " Revision "
                + revision;
        email.setSubject(subj);
        email.setSender(config.getProperty("sender"));
        email.setSMTP(config.getProperty("smtp"));
        if (hostname.equals(config.get("buildhost"))) {
            Log.info("Emailling all recipients " + subj);
            for (String recipient : config.getProperty("recipients").split(","))
                email.addRecipient(recipient.trim());
        } else {// Running on your own machine, just send it to yourself
            Log.info("Emailling local runner " + subj);
            email.addRecipient(System.getProperty("user.name") + "@ara.com");
        }
        html.append("<html>");
        html.append("<body>");

        // Get a list of all the results files we have to work with

        File vdir = new File("./Scenarios/Validation/");
        String[] vFiles = vdir.list();

        // Now read in the spreadsheet      
        FileInputStream xlFile = new FileInputStream(directoryName + "/" + fileName);
        XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);

        FormulaEvaluator evaluator = xlWBook.getCreationHelper().createFormulaEvaluator();
        List<ValidationRow> badSheets = new ArrayList<ValidationRow>();
        Map<String, List<ValidationRow>> tables = new HashMap<String, List<ValidationRow>>();
        Map<String, List<ValidationRow>> tableErrors = new HashMap<String, List<ValidationRow>>();
        List<ValidationRow> allRows = new ArrayList<ValidationRow>();
        for (int i = 0; i < xlWBook.getNumberOfSheets(); i++) {
            XSSFSheet xlSheet = xlWBook.getSheetAt(i);
            Log.info("Processing Sheet : " + xlSheet.getSheetName());
            String sheetName = xlSheet.getSheetName().trim().replaceAll(" ", "");

            List<String> sheetFiles = new ArrayList<String>();
            String rSheetName = sheetName + "ValidationResults.txt";
            File rFile = new File(rSheetName);
            if (!rFile.exists()) {
                // Search for any file starting with the sheet name
                for (String f : vFiles)
                    if (f.startsWith(sheetName) && f.endsWith(".txt"))
                        sheetFiles.add(f);
            } else
                sheetFiles.add(rSheetName);

            for (String resultsName : sheetFiles) {
                Log.info("Processing " + resultsName);
                try {
                    // Look for a results file
                    CSVContents results = new CSVContents("./Scenarios/Validation/" + resultsName);
                    results.readAll(resultData);
                    // Find any assessments
                    assessments = new HashMap<String, SEPatientAssessment>();
                    for (String vFile : vFiles) {
                        if (vFile.indexOf(sheetName) > -1 && vFile.indexOf('@') > -1) {
                            Object aData = CDMSerializer.readFile("./Scenarios/Validation/" + vFile);
                            if (aData instanceof PatientAssessmentData) {
                                String aClassName = "SE" + aData.getClass().getSimpleName();
                                aClassName = aClassName.substring(0, aClassName.indexOf("Data"));
                                try {
                                    Class<?> aClass = Class.forName(
                                            "mil.tatrc.physiology.datamodel.patient.assessments." + aClassName);
                                    SEPatientAssessment a = (SEPatientAssessment) aClass.newInstance();
                                    aClass.getMethod("load", aData.getClass()).invoke(a, aData);
                                    assessments.put(vFile, a);
                                } catch (Exception ex) {
                                    Log.error("Unable to load assesment xml " + vFile, ex);
                                }
                            } else
                                Log.error(vFile + " is named like a patient assessment, but its not?");
                        }
                    }
                } catch (Exception ex) {
                    ValidationRow vRow = new ValidationRow();
                    vRow.header = sheetName;
                    vRow.error = danger + "No results found for sheet " + endSpan;
                    badSheets.add(vRow);
                    continue;
                }
                // Is this patient validation?
                patient = null;
                if (TABLE_TYPE.equals("Patient")) {
                    // Patient Name is encoded in the naming convention (or else it needs to be)
                    String patientName = resultsName.substring(resultsName.lastIndexOf("-") + 1,
                            resultsName.indexOf("Results"));
                    patient = new SEPatient();
                    patient.load((PatientData) CDMSerializer.readFile("./stable/" + patientName + ".xml"));
                }

                allRows.clear();
                tables.clear();
                tableErrors.clear();
                // Read the sheet and process all the validation data rows
                try {

                    int rows = xlSheet.getPhysicalNumberOfRows();
                    for (int r = 0; r < rows; r++) {
                        XSSFRow row = xlSheet.getRow(r);
                        if (row == null)
                            continue;
                        int cells = 11;//row.getPhysicalNumberOfCells();
                        XSSFCell cell = row.getCell(0);
                        if (cell == null)
                            continue;
                        // Check to see if this row is a header
                        String cellValue = cell.getStringCellValue();
                        if (cellValue == null || cellValue.isEmpty())
                            continue;// No property, skip it
                        cellValue = row.getCell(1).getStringCellValue();
                        if (cellValue != null && cellValue.equals("Units"))
                            continue;// Header                      

                        ValidationRow vRow = new ValidationRow();
                        allRows.add(vRow);
                        for (int c = 0; c <= cells; c++) {
                            cellValue = null;
                            cell = row.getCell(c);
                            if (cell == null)
                                continue;
                            switch (cell.getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                cellValue = Double.toString(cell.getNumericCellValue());
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                cellValue = cell.getStringCellValue();
                                break;
                            case XSSFCell.CELL_TYPE_FORMULA:
                                switch (evaluator.evaluateFormulaCell(cell)) {
                                case XSSFCell.CELL_TYPE_NUMERIC:
                                    cellValue = String.format("%." + 3 + "g", cell.getNumericCellValue());
                                    break;
                                case XSSFCell.CELL_TYPE_STRING:
                                    cellValue = cell.getStringCellValue();
                                    break;
                                }

                            }

                            switch (c) {
                            case 0://A                 
                                Log.info("Processing " + cellValue);
                                vRow.name = cellValue.trim().replaceAll(" ", "");
                                String prop = vRow.name;
                                if (vRow.name.indexOf('*') != -1)
                                    prop = prop.substring(0, prop.length() - 1);
                                vRow.header = vRow.name;
                                break;
                            case 1://B
                                if (cellValue != null && !cellValue.equalsIgnoreCase("none")
                                        && !cellValue.equalsIgnoreCase("n\\a")
                                        && !cellValue.equalsIgnoreCase("n/a")) {
                                    vRow.unit = cellValue;
                                }
                                if (vRow.unit != null && !vRow.unit.isEmpty())
                                    vRow.header += "(" + vRow.unit + ")";
                                break;
                            case 2://C
                                if (cellValue != null) {
                                    String unit = null;
                                    int u = cellValue.indexOf("(");
                                    if (u > -1) {
                                        unit = cellValue.substring(u + 1, cellValue.indexOf(")"));
                                        cellValue = cellValue.substring(0, u);
                                    }
                                    vRow.dType = DataType.valueOf(cellValue);
                                    if (vRow.dType == DataType.MeanPerWeight
                                            || vRow.dType == DataType.WaveformMinPerWeight
                                            || vRow.dType == DataType.WaveformMaxPerWeight) {
                                        vRow.weightUnit = unit;
                                    }
                                }
                                break;
                            case 3://D
                                // Replace any return characters with empty
                                if (patient != null && vRow.name.indexOf('*') == -1) {
                                    try {
                                        Method has = SEPatient.class.getMethod("has" + vRow.name);
                                        if ((Boolean) has.invoke(patient)) {
                                            Method get = SEPatient.class.getMethod("get" + vRow.name);
                                            SEScalar s = ((SEScalar) get.invoke(patient));
                                            vRow.refValue = s.getValue(vRow.unit);
                                            vRow.refValues = cellValue;
                                            break;
                                        } else {
                                            Log.error("Patient does not have a value for " + vRow.name);
                                        }
                                    } catch (Exception ex) {
                                        // Nothing to do, row is not a patient property
                                    }
                                }
                                if (cellValue == null)
                                    vRow.refValues = null;
                                else
                                    vRow.refValues = cellValue.replace("\n", "");

                                break;
                            case 4://E
                                // Replace any return characters with empty
                                if (cellValue != null)
                                    cellValue = cellValue.replace("\n", "");
                                vRow.refCites = cellValue;
                                break;
                            case 5://F Reference Page (Internal only)
                                break;
                            case 6://G Notes
                                if (cellValue != null)
                                    vRow.notes = cellValue;
                                break;// Skipping for now
                            case 7://H Internal Notes (Internal only)
                                break;
                            case 8://I Reading (Internal only)
                                break;
                            case 9://J Table (Internal only)
                                if (cellValue == null)
                                    cellValue = "";
                                vRow.table = cellValue;
                                if (patient != null)
                                    vRow.table = patient.getName() + "Patient" + cellValue;
                                break;
                            case 10://K ResultFile (Internal only)
                                if (cellValue != null)
                                    vRow.resultFile = cellValue;
                                break;
                            case 11://L Mantissa Digits
                                if (cellValue != null)
                                    vRow.doubleFormat = cellValue;
                                if (patient != null && vRow.dType != DataType.Patient2SystemMean)
                                    vRow.refValues = String.format("%." + vRow.doubleFormat, vRow.refValue);
                                break;
                            }
                        }
                    }
                } catch (Exception ex) {
                    Log.error("Error reading row", ex);
                    ValidationRow vRow = new ValidationRow();
                    vRow.header = sheetName;
                    vRow.error = danger + "Sheet has errors" + endSpan;
                    badSheets.add(vRow);
                    continue;
                }

                // Sort all of our rows, and validate them
                for (ValidationRow vRow : allRows) {
                    if (vRow.table.isEmpty())
                        vRow.table = sheetName;//Default table is the sheet name
                    if (!tables.containsKey(vRow.table))
                        tables.put(vRow.table, new ArrayList<ValidationRow>());
                    if (!tableErrors.containsKey(vRow.table))
                        tableErrors.put(vRow.table, new ArrayList<ValidationRow>());
                    if (buildExpectedHeader(vRow)) {
                        Log.info("Validating " + vRow.header);
                        if (validate(vRow)) {
                            tables.get(vRow.table).add(vRow);
                        } else
                            tableErrors.get(vRow.table).add(vRow);
                    } else
                        tableErrors.get(vRow.table).add(vRow);
                }

                for (String name : tables.keySet()) {
                    if (name.contains("All"))
                        continue;
                    List<ValidationRow> t = tables.get(name);
                    WriteHTML(t, name);
                    WriteDoxyTable(t, name, destinationDirectory);
                    if (name.equalsIgnoreCase(sheetName)) {
                        List<String> properties = new ArrayList<String>();
                        for (ValidationRow vRow : t)
                            properties.add(vRow.name);
                        for (ValidationRow vRow : tableErrors.get(name))
                            properties.add(vRow.name);
                        CrossCheckValidationWithSchema(properties, tableErrors.get(name), name);
                    }
                    WriteHTML(tableErrors.get(name), name + "Errors");
                    if (patient != null)
                        CustomMarkdown(patient.getName(), destinationDirectory);
                }
            }
        }
        xlWBook.close();
        WriteHTML(badSheets, fileName + " Errors");
        html.append("</body>");
        html.append("</html>");
        if (sendEmail)
            email.sendHTML(html.toString());
    } catch (Exception ex) {
        Log.error("Error processing spreadsheet " + fileName, ex);
    }
    // Just for fun, I am going to create a single md file with ALL the tables in it

    try {
        String line;
        File vDir = new File(destinationDirectory);
        PrintWriter writer = new PrintWriter(destinationDirectory + "/AllValidationTables.md", "UTF-8");

        for (String fName : vDir.list()) {
            if (fName.equals("AllValidationTables.md"))
                continue;
            if (new File(fName).isDirectory())
                continue;
            FileReader in = new FileReader(destinationDirectory + "/" + fName);
            BufferedReader inFile = new BufferedReader(in);
            writer.println(fName);
            while ((line = inFile.readLine()) != null)
                writer.println(line);
            inFile.close();
            writer.println("<br>");
        }
        writer.close();
    } catch (Exception ex) {
        Log.error("Unable to create single validation table file.", ex);
    }
}

From source file:mil.tatrc.physiology.utilities.testing.validation.ValidationMatrix.java

License:Apache License

public static void convert(String from, String to) throws IOException {
    FileInputStream xlFile = new FileInputStream(new File(from));
    // Read workbook into HSSFWorkbook
    XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
    List<SheetSummary> sheetSummaries = new ArrayList<SheetSummary>();// has to be an ordered list as sheet names can only be so long
    Map<String, String> refs = new HashMap<String, String>();

    List<Sheet> Sheets = new ArrayList<Sheet>();

    for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) {
        XSSFSheet xlSheet = xlWBook.getSheetAt(s);
        Log.info("Processing Sheet : " + xlSheet.getSheetName());
        if (xlSheet.getSheetName().equals("Summary")) {
            int rows = xlSheet.getPhysicalNumberOfRows();
            for (int r = 1; r < rows; r++) {
                XSSFRow row = xlSheet.getRow(r);
                if (row == null)
                    continue;
                SheetSummary ss = new SheetSummary();
                sheetSummaries.add(ss);//  w  ww. j a v a2s.  c o  m
                ss.name = row.getCell(0).getStringCellValue();
                ss.description = row.getCell(1).getStringCellValue();
                ss.validationType = row.getCell(2).getStringCellValue();
            }
        } else if (xlSheet.getSheetName().equals("References")) {
            int rows = xlSheet.getPhysicalNumberOfRows();
            for (int r = 1; r < rows; r++) {
                XSSFRow row = xlSheet.getRow(r);
                if (row == null)
                    continue;
                refs.put("\\[" + r + "\\]", "@cite " + row.getCell(1).getStringCellValue());
            }
        } else {
            int rows = xlSheet.getPhysicalNumberOfRows();
            Sheet sheet = new Sheet();
            sheet.summary = sheetSummaries.get(s - 2);
            Sheets.add(sheet);

            int cells = xlSheet.getRow(0).getPhysicalNumberOfCells();

            for (int r = 0; r < rows; r++) {
                XSSFRow row = xlSheet.getRow(r);
                if (row == null)
                    continue;

                String cellValue = null;

                for (int c = 0; c < cells; c++) {
                    List<Cell> column;
                    if (r == 0) {
                        column = new ArrayList<Cell>();
                        sheet.table.add(column);
                    } else {
                        column = sheet.table.get(c);
                    }

                    XSSFCell cell = row.getCell(c);
                    if (cell == null) {
                        column.add(new Cell("", Agreement.NA, refs));
                        continue;
                    }
                    cellValue = null;
                    switch (cell.getCellType()) {
                    case XSSFCell.CELL_TYPE_NUMERIC:
                        cellValue = Double.toString(cell.getNumericCellValue());
                        break;
                    case XSSFCell.CELL_TYPE_STRING:
                        cellValue = cell.getStringCellValue();
                        break;
                    }
                    if (cellValue == null || cellValue.isEmpty())
                        column.add(new Cell("", Agreement.NA, refs));
                    else {
                        Agreement a = Agreement.NA;
                        XSSFColor color = cell.getCellStyle().getFillForegroundColorColor();
                        if (color != null) {
                            byte[] rgb = color.getRGB();
                            if (rgb[0] < -25 && rgb[1] > -25 && rgb[2] < -25) {
                                a = Agreement.Good;
                                sheet.summary.goodAgreement++;
                            } else if (rgb[0] > -25 && rgb[1] > -25 && rgb[2] < -25) {
                                a = Agreement.Ok;
                                sheet.summary.okAgreement++;
                            } else if (rgb[0] > -25 && rgb[1] < -25 && rgb[2] < -25) {
                                a = Agreement.Bad;
                                sheet.summary.badAgreement++;
                            }
                        }
                        column.add(new Cell(cellValue, a, refs));
                    }
                }
            }
        }
    }
    xlWBook.close();
    xlFile.close(); //close xls

    // Generate our Tables for each Sheet
    PrintWriter writer = null;
    try {
        String name = from.substring(from.lastIndexOf('/') + 1, from.lastIndexOf('.')) + "Scenarios";

        writer = new PrintWriter(to + name + "Summary.md", "UTF-8");
        writer.println(
                "|Scenario|Description|Validation Type|Good agreement|General agreement with deviations|Some major disagreements|");
        writer.println("|--- |--- |:---: |:---: |:---: |:---: |");
        for (Sheet sheet : Sheets) {
            writer.println("|" + sheet.summary.name + "|" + sheet.summary.description + "|"
                    + sheet.summary.validationType + "|" + success + sheet.summary.goodAgreement + endSpan + "|"
                    + warning + sheet.summary.okAgreement + endSpan + "|" + danger + sheet.summary.badAgreement
                    + endSpan + "|");
        }
        writer.close();

        // Create file and start the table
        writer = new PrintWriter(to + name + ".md", "UTF-8");
        writer.println(name + " {#" + name + "}");
        writer.println("=======");
        writer.println();

        writer.println();

        for (Sheet sheet : Sheets) {
            Log.info("Writing table : " + sheet.summary.name);
            writer.println("## " + sheet.summary.name);

            writer.println(sheet.summary.description);
            writer.println("We used a " + sheet.summary.validationType + " validation method(s).");
            writer.println("");

            for (int row = 0; row < sheet.table.get(0).size(); row++) {
                for (int col = 0; col < sheet.table.size(); col++) {
                    writer.print("|" + sheet.table.get(col).get(row).text);
                }
                writer.println("|");
                if (row == 0) {
                    for (int col = 0; col < sheet.table.size(); col++) {
                        writer.print("|---   ");
                    }
                    writer.println("|");
                }
            }
            writer.println();
            writer.println();
        }
        writer.close();
    } catch (Exception ex) {
        Log.error("Error writing tables for " + from, ex);
        writer.close();
    }
}

From source file:mpqq.MPQQ.java

/**
 * @param args the command line arguments
 *///from  w  w w .j a  v  a 2s. com
public static void main(String[] args) {

    try {
        //Read Reference File
        FileInputStream referenceFile = new FileInputStream(
                new File("C:\\Personal\\09168336\\Documents\\iRef.xlsx"));
        XSSFWorkbook reference = new XSSFWorkbook(referenceFile);
        reference.close();

        FileInputStream mpqqFile = new FileInputStream(
                new File("C:\\Personal\\09168336\\Documents\\mpqq.xlsm"));
        XSSFWorkbook mpqq = new XSSFWorkbook(mpqqFile);
        mpqqFile.close();
        int referenceStartRow = 156;

        //Create a MPQQ for each supplier in the reference document
        String currentSupplier = reference.getSheetAt(USE_FOR_TAB1).getRow(referenceStartRow)
                .getCell(T2PEPSICO_SUPPLIER_SITE_NAME).getStringCellValue();

        System.out.println(currentSupplier);

        mpqq = procTab1(reference, mpqq, referenceStartRow);
        FileOutputStream outFile = new FileOutputStream(
                new File("C:\\Personal\\09168336\\Documents\\mpqq.xlsm"));
        mpqq.write(outFile);
        outFile.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Testing");
}

From source file:nc.noumea.mairie.appock.services.impl.ImportExcelServiceImpl.java

License:Open Source License

@Override
public List<String> importCatalogue(Media media, Catalogue catalogue) throws IOException {
    List<String> messages = new ArrayList<>();
    XSSFWorkbook workbook = new XSSFWorkbook(media.getStreamData());
    XSSFSheet firstSheet = workbook.getSheetAt(0);

    int nbLigneTraite = 0;
    for (int ligne = 1; ligne < firstSheet.getPhysicalNumberOfRows(); ligne++) {
        try {/*  w  w  w.j a v  a  2 s. co m*/
            traiterLigne(firstSheet, ligne, media, catalogue);
            nbLigneTraite++;
        } catch (ImportExcelException e) {
            messages.add(e.getMessage());
        }
    }

    if (!messages.isEmpty()) {
        messages.add(0, "Certaines rfrences n'ont pas pu tre importes : ");
    }

    StringBuilder statistiques = new StringBuilder("\nStatistiques :");
    statistiques.append("\n - Nombre de lignes total : " + (firstSheet.getPhysicalNumberOfRows() - 1));
    statistiques.append("\n - Nombre de rfrences importes : " + nbLigneTraite);
    statistiques.append("\n - Nombre de rfrences ignores : "
            + (firstSheet.getPhysicalNumberOfRows() - 1 - nbLigneTraite));
    messages.add(statistiques.toString());

    workbook.close();
    return messages;
}

From source file:negocio.parser.ExcelReader.java

@Override
public IExcelContent leerArchivo(String ruta) throws Exception {
    java.util.Date date = new java.util.Date();
    Date entrada = new Date(date.getTime());
    IExcelContent ec = ExcelContent.getInstantiateExcelContent();
    try {/* ww  w.ja  v  a2 s . c  om*/
        LogDAO dao = new LogDAO();
        LogDTO dto = new LogDTO("Leer archivo", "Comienzo de lectura de archivo", entrada.toString(),
                entrada.toString());
        dao.registrarLog(dto);
        File archivo = new File(ruta);
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(archivo)); //crear un libro excel
        XSSFSheet sheet = workbook.getSheetAt(0); //acceder a la primera hoja
        Iterator<Row> rowIterator = sheet.iterator();
        Row row;
        boolean sw = true;
        ArrayList<List<String>> datos = new ArrayList<>();
        while (rowIterator.hasNext()) {

            row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            Cell celda;
            List<String> fila = new ArrayList<>();
            while (cellIterator.hasNext()) {
                celda = cellIterator.next();
                String dato = "";
                switch (celda.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    if (HSSFDateUtil.isCellDateFormatted(celda)) {
                        dato = celda.getDateCellValue().toString();
                    } else {
                        dato = celda.getNumericCellValue() + "";
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    dato = celda.getStringCellValue();
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    dato = celda.getBooleanCellValue() + "";
                    break;
                }
                fila.add(dato);
            }
            if (sw) {
                sw = false;
                ec.setTitulos(fila);
            } else {
                datos.add(fila);
            }
        }
        ec.setDatos(datos);
        workbook.close();
        return ec;
    } catch (IOException ex) {
        Logger.getLogger(ExcelReader.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;

}

From source file:nl.detoren.ijc.io.OutputExcel.java

License:Open Source License

/**
 * Create the Excel version of the sheet Original Empty file is stored in
 * Empty.xlsx Create version with round matches is stored in Indeling.xlsx
 *
 * @param wedstrijden//from w  w  w.  j  a  v a 2 s .  co m
 *            The round to store in the Excel file
 */
public boolean export(Wedstrijden wedstrijden) {
    try {
        logger.log(Level.INFO, "Wedstrijden wegschrijven naar Excel");

        int periode = wedstrijden.getPeriode();
        int ronde = wedstrijden.getRonde();
        String rpString = "Periode " + periode + ", Ronde " + ronde;
        String datum = new SimpleDateFormat("dd-MM-yyyy HH:mm").format(Calendar.getInstance().getTime());

        // Open the empty schedule file, matches are stored in the
        // second sheet (id = 1)
        FileInputStream file = new FileInputStream("Template.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        ArrayList<Groepswedstrijden> gws = wedstrijden.getGroepswedstrijden();
        for (Groepswedstrijden gw : gws) {
            int groepID = gw.getNiveau();
            int nrSeries = gw.getSeries().size();
            // Open sheet voor deze groep
            XSSFSheet sheet = workbook.getSheetAt(groepID);
            workbook.setSheetName(groepID, Groep.geefNaam(groepID));
            updateCell(sheet, 2, 8, rpString);
            updateCell(sheet, 2, 4, datum);
            // Export Series
            int currentRow = 5;
            for (int s = 0; s < nrSeries; ++s) { // For each serie
                Serie serie = gw.getSerie(s);
                updateCell(sheet, currentRow, 2, "Serie " + (s + 1));
                borderLeft(getCell(sheet, currentRow, 1));
                borderLeft(getCell(sheet, currentRow + 1, 1));
                borderRight(getCell(sheet, currentRow, 9));
                borderRight(getCell(sheet, currentRow + 1, 9));
                currentRow += 2;
                for (Wedstrijd w : serie.getWedstrijden()) {
                    exportWedstrijd(sheet, w, currentRow);
                    borderLeft(getCell(sheet, currentRow, 1));
                    borderLeft(getCell(sheet, currentRow + 1, 1));
                    borderRight(getCell(sheet, currentRow, 9));
                    borderRight(getCell(sheet, currentRow + 1, 9));
                    currentRow += 2;
                }
            }
            // Export trio
            ArrayList<Wedstrijd> trio = gw.getTriowedstrijden();
            if (trio != null && trio.size() > 0) {
                updateCell(sheet, currentRow, 2, "Trio");
                borderLeft(getCell(sheet, currentRow, 1));
                borderLeft(getCell(sheet, currentRow + 1, 1));
                borderRight(getCell(sheet, currentRow, 9));
                borderRight(getCell(sheet, currentRow + 1, 9));
                currentRow += 2;
                for (Wedstrijd w : trio) {
                    exportWedstrijd(sheet, w, currentRow);
                    borderLeft(getCell(sheet, currentRow, 1));
                    borderLeft(getCell(sheet, currentRow + 1, 1));
                    borderRight(getCell(sheet, currentRow, 9));
                    borderRight(getCell(sheet, currentRow + 1, 9));
                    currentRow += 2;
                }
            }
            currentRow--;
            for (int j = 2; j <= 8; j++)
                borderBottom(getCell(sheet, currentRow, j));
            borderLeftBottom(getCell(sheet, currentRow, 1));
            borderRightBottom(getCell(sheet, currentRow, 9));
        }
        // Close input file
        file.close();
        // Store Excel to new file
        String dirName = "R" + periode + "-" + ronde;
        new File(dirName).mkdirs();
        String filename = dirName + File.separator + "Indeling " + periode + "-" + ronde + ".xlsx";
        File outputFile = new File(filename);
        FileOutputStream outFile = new FileOutputStream(outputFile);
        workbook.write(outFile);
        // Close output file
        workbook.close();
        outFile.close();
        // And open it in the system editor
        Desktop.getDesktop().open(outputFile);
        return true;
    } catch (Exception e) {
        logger.log(Level.WARNING, "Error writing output: " + e.toString());
        FoutMelding.melding("Fout bij opslaan Excel bestand: " + e.getMessage());
        return false;
    }
}