Example usage for org.apache.poi.xssf.usermodel XSSFCell getStringCellValue

List of usage examples for org.apache.poi.xssf.usermodel XSSFCell getStringCellValue

Introduction

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

Prototype

@Override
public String getStringCellValue() 

Source Link

Document

Get the value of the cell as a string

For numeric cells we throw an exception.

Usage

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

License:Apache License

protected static Map<String, SENutrition> readNutrition(XSSFSheet xlSheet) {
    String property, value, unit;
    SENutrition meal;/* w  w w  .  j a va  2s  .  com*/
    Map<String, SENutrition> map = new HashMap<String, SENutrition>();
    List<SENutrition> meals = new ArrayList<SENutrition>();
    try {
        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 (r == 0) {// Allocate the number of environments we have
                for (int i = 1; i < cells; i++)
                    meals.add(new SENutrition());
            }
            property = row.getCell(0).getStringCellValue();
            if (property == null || property.isEmpty())
                continue;
            Log.info("Processing Nutrition Field : " + property);
            for (int c = 1; c < cells; c++) {
                String cellValue = null;
                XSSFCell cell = row.getCell(c);
                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())
                    continue;
                int split = cellValue.indexOf(" ");
                // Pull The Value
                if (split == -1) {
                    value = cellValue;
                    unit = "";
                } else {
                    value = cellValue.substring(0, split);
                    unit = cellValue.substring(split + 1);
                }
                meal = meals.get(c - 1);
                if (property.equals("Name")) {
                    map.put(cellValue, meal);
                    continue;
                }
                if (!setProperty(meal, property, value, unit)) {
                    Log.error("Error pulling" + property + " from " + cellValue);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        Log.error("Error reading XLS", ex);
        return null;
    }
    return map;
}

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 {//w w  w  .j a  v a2s  . c o  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);//from w ww .j ava 2 s  .  c om
                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:mx.infotec.dads.arq.excel.ImplementExcel.java

public String getStringCellValue(XSSFCell cell) {
    String value;//w w w .  j a  va  2 s  .c  o m
    switch (cell.getCellType()) {
    case XSSFCell.CELL_TYPE_STRING:
        value = cell.getStringCellValue() + " ";
        break;
    case XSSFCell.CELL_TYPE_NUMERIC:
        Double n = cell.getNumericCellValue();
        if (HSSFDateUtil.isCellDateFormatted(cell)) {
            value = cell.getDateCellValue().toString();
        } else {
            value = n + " ";
        }
        break;
    case XSSFCell.CELL_TYPE_BOOLEAN:
        value = cell.getBooleanCellValue() + " ";
        break;
    case XSSFCell.CELL_TYPE_FORMULA:
        value = cell.getCellFormula();
        break;
    case XSSFCell.CELL_TYPE_ERROR:
        value = cell.getErrorCellString();
        break;
    default:
        value = "error";
        break;
    }

    return value;
}

From source file:mx.infotec.dads.arq.excel.ImplementExcel.java

public Object getCellValue(XSSFCell cell) {
    Object value;//from www .  j  ava 2  s  . co  m
    switch (cell.getCellType()) {
    case XSSFCell.CELL_TYPE_STRING:
        value = cell.getStringCellValue();
        break;
    case XSSFCell.CELL_TYPE_NUMERIC:
        if (HSSFDateUtil.isCellDateFormatted(cell)) {
            value = cell.getDateCellValue();
        } else {
            value = cell.getNumericCellValue();
        }
        break;
    case XSSFCell.CELL_TYPE_BOOLEAN:
        value = cell.getBooleanCellValue();
        break;
    case XSSFCell.CELL_TYPE_FORMULA:
        value = cell.getCellFormula();
        break;
    case XSSFCell.CELL_TYPE_ERROR:
        value = cell.getErrorCellString();
        break;
    default:
        value = "error";
        break;
    }

    return value;
}

From source file:nc.noumea.mairie.appock.util.StockSpreadsheetImporter.java

License:Open Source License

private static void traiterLigne(int ligne, XSSFSheet worksheet, Service service, StockService stockService)
        throws ImportExcelException {
    XSSFCell referenceCell = worksheet.getRow(ligne).getCell(1);
    if (StringUtils.isBlank(referenceCell.getRawValue())) {
        throw new ImportExcelException(ligne + 1, "La rfrence est introuvable");
    }/*from   ww  w.  j  av a  2 s . c o  m*/
    String reference = referenceCell.getStringCellValue();

    XSSFCell stockReelCell = worksheet.getRow(ligne).getCell(4);
    if (StringUtils.isBlank(stockReelCell.getRawValue())) {
        throw new ImportExcelException(ligne + 1, reference, "La quantit relle n'est pas renseigne");
    }

    if (stockReelCell.getCellTypeEnum() != CellType.NUMERIC) {
        throw new ImportExcelException(ligne + 1, reference, "La cellule 'Stock rl' n'est pas un entier");
    }
    double value = stockReelCell.getNumericCellValue();
    int stockReel = (int) value;
    if (value != stockReel) {
        throw new ImportExcelException(ligne + 1, reference, "La cellule 'Stock rl' n'est pas un entier");
    }
    updateStock(service, reference, stockReel, stockService, ligne);
}

From source file:no.sintef.ict.splcatool.XLSXLib.java

License:Open Source License

public static String getCSV(File file) throws IOException {
    String filename = file.getAbsoluteFile().toString();
    FileInputStream fis = new FileInputStream(filename);

    XSSFWorkbook workbook = new XSSFWorkbook(fis);
    XSSFSheet sheet = workbook.getSheetAt(0);

    //System.out.println(" number of rows"+ sheet.getLastRowNum());
    String csv = "";
    int w = Integer.MAX_VALUE;
    outerloop: for (Row r : sheet) {
        int x = 0;
        XSSFRow row = (XSSFRow) r;/*from w  w w . j a  va 2 s  .c om*/
        for (Cell c : row) {
            if (x >= w)
                break;
            XSSFCell cell = (XSSFCell) c;
            String v = "";
            if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                v = cell.getStringCellValue();
            } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
                v = "" + (int) cell.getNumericCellValue();
            } else {
                System.out.println("Unknown type " + cell.getCellType() + " " + cell.getRawValue());
                System.exit(-1);
            }
            //System.out.println(v + ", " + x + ", " + w);
            if (x == 0 && v.equals("#end"))
                break outerloop;
            if (v.equals("#end")) {
                w = x;
                break;
            }
            csv += v + ";";
            x++;
        }
        csv += "\n";
    }

    //csv = csv.substring(0, csv.length()-1);
    //System.out.println(csv);

    return csv;
}

From source file:offishell.excel.Excel.java

License:MIT License

/**
 * <p>/*  w ww. j  a  v  a 2s  .com*/
 * ??????????
 * </p>
 * 
 * @param cellName ??
 * @return
 */
public Signal<Row> takeBy(String cellName) {
    int index = indexOfHeader(cellName);

    return new Signal<Row>((observer, disposer) -> {
        for (int i = 1; i < sheet.getLastRowNum(); i++) {
            XSSFRow row = sheet.getRow(i);

            if (row != null) {
                XSSFCell cell = row.getCell(index);

                if (cell != null) {
                    switch (cell.getCellTypeEnum()) {
                    case BLANK:
                        break;

                    case STRING:
                        String value = cell.getStringCellValue();

                        if (value != null && !value.isEmpty()) {
                            observer.accept(new Row(row));
                        }
                        break;

                    default:
                        observer.accept(new Row(row));
                        break;
                    }
                }
            }
        }
        return disposer;
    });
}

From source file:org.addition.epanet.network.io.input.ExcelParser.java

License:Open Source License

private String convertCell(XSSFCell cell) throws ENException {
    if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
        if (timeStyles.contains(cell.getCellStyle()))
            return Utilities.getClockTime(Math.round(cell.getNumericCellValue() * 86400));

        return Double.toString(cell.getNumericCellValue());
    } else if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
        return cell.getStringCellValue();
    else//from  w  w  w . jav  a  2s .c o m
        throw new ENException(201);
}

From source file:org.apache.ofbiz.pricat.AbstractPricatParser.java

License:Apache License

/**
 * Get data by version definition.//from  w w  w .  j  a va 2 s. c o m
 * 
 * @param row
 * @param colNames 
 * @param size 
 * @return
 */
public List<Object> getCellContents(XSSFRow row, List<Object[]> colNames, int size) {
    List<Object> results = new ArrayList<Object>();
    boolean foundError = false;
    if (isEmptyRow(row, size, true)) {
        return null;
    }
    for (int i = 0; i < size; i++) {
        XSSFCell cell = null;
        if (row.getPhysicalNumberOfCells() > i) {
            cell = row.getCell(i);
        }
        if (cell == null) {
            if (((Boolean) colNames.get(i)[2]).booleanValue()) {
                report.print(UtilProperties.getMessage(resource, "ErrorColCannotEmpty",
                        new Object[] { colNames.get(i)[0] }, locale), InterfaceReport.FORMAT_WARNING);
                errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource,
                        "ErrorColCannotEmpty", new Object[] { colNames.get(i)[0] }, locale));
                foundError = true;
                continue;
            } else {
                cell = row.createCell(i);
            }
        }
        int cellType = cell.getCellType();
        String cellValue = formatter.formatCellValue(cell);
        if (UtilValidate.isNotEmpty(cellValue)) {
            if (cellType == XSSFCell.CELL_TYPE_FORMULA) {
                cellValue = BigDecimal.valueOf(cell.getNumericCellValue())
                        .setScale(FinAccountHelper.decimals, FinAccountHelper.rounding).toString();
                report.print(((i == 0) ? "" : ", ") + cellValue, InterfaceReport.FORMAT_NOTE);
            } else {
                report.print(((i == 0) ? "" : ", ") + cellValue, InterfaceReport.FORMAT_NOTE);
            }
        } else {
            report.print(((i == 0) ? "" : ","), InterfaceReport.FORMAT_NOTE);
        }
        if (((Boolean) colNames.get(i)[2]).booleanValue() && UtilValidate.isEmpty(cellValue)) {
            report.print(UtilProperties.getMessage(resource, "ErrorColCannotEmpty",
                    new Object[] { colNames.get(i)[0] }, locale), InterfaceReport.FORMAT_WARNING);
            errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource,
                    "ErrorColCannotEmpty", new Object[] { colNames.get(i)[0] }, locale));
            foundError = true;
            results.add(null);
            continue;
        }
        if (((Boolean) colNames.get(i)[2]).booleanValue() && cellType != (int) colNames.get(i)[1]) {
            // String warningMessage = "";
            if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_STRING) {
                results.add(cellValue);
            } else if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_NUMERIC) {
                if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING) {
                    cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                }
                try {
                    results.add(BigDecimal.valueOf(Double.parseDouble(cell.getStringCellValue()))
                            .setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
                } catch (NumberFormatException e) {
                    results.add(null);
                    errorMessages.put(new CellReference(cell),
                            UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
                }
            }
        } else {
            if (UtilValidate.isEmpty(cellValue)) {
                results.add(null);
                continue;
            }
            if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_STRING) {
                if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                    results.add(cell.getStringCellValue());
                } else {
                    results.add(cellValue);
                }
            } else if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_NUMERIC) {
                if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                    try {
                        results.add(BigDecimal.valueOf(Double.valueOf(cell.getStringCellValue())));
                    } catch (NumberFormatException e) {
                        results.add(null);
                        errorMessages.put(new CellReference(cell),
                                UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
                    }
                } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
                    try {
                        results.add(BigDecimal.valueOf(cell.getNumericCellValue())
                                .setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
                    } catch (NumberFormatException e) {
                        results.add(null);
                        errorMessages.put(new CellReference(cell),
                                UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
                    }
                } else {
                    try {
                        results.add(BigDecimal.valueOf(Double.valueOf(cellValue))
                                .setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
                    } catch (NumberFormatException e) {
                        results.add(null);
                        errorMessages.put(new CellReference(cell),
                                UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
                    }
                }
            }
        }
    }
    if (foundError) {
        return null;
    }
    return results;
}