Example usage for org.apache.poi.ss.usermodel DataFormatter formatCellValue

List of usage examples for org.apache.poi.ss.usermodel DataFormatter formatCellValue

Introduction

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

Prototype

public String formatCellValue(Cell cell) 

Source Link

Document

Returns the formatted value of a cell as a String regardless of the cell type.

Usage

From source file:RefDiviedMain.java

License:Creative Commons License

public static Element getTable(String name) {
    DataFormatter formatter = new DataFormatter(Locale.US);
    if (name == null) {
        DocumentBuilder db = null;
        try {//from w  w  w.j  a  va2s.c o m
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            ta.append("\nerrors happen:\n");
            ta.append(ex.getMessage() + "\n");
        }
        doc = db.newDocument();
    }

    if (name == null) {
        name = "C:\\Users\\DLiu1\\Documents\\NetBeansProjects\\Simon\\dist\\Table 1";
    }
    String fileName = name + ".xls";

    File aaa = new File(fileName);
    if (!aaa.exists()) {
        RefDiviedMain
                .error(fileName + " doesn't exist, please copy the " + fileName + " into the same folder!");
        return null;
    }
    Element tableFrame = null;
    try {

        tableFrame = doc.createElement("table");

        tableFrame.setAttribute("frame", "hsides");

        tableFrame.setAttribute("rules", "groups");
        Element thead = doc.createElement("thead");
        Element tbody = doc.createElement("tbody");
        tableFrame.appendChild(thead);
        tableFrame.appendChild(tbody);
        /** Creating Input Stream**/
        //InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
        FileInputStream myInput = new FileInputStream(aaa);

        /** Create a POIFSFileSystem object**/
        POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

        /** Create a workbook using the File System**/
        HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

        /** Get the first sheet from workbook**/
        HSSFSheet mySheet = myWorkBook.getSheetAt(0);

        /** We now need something to iterate through the cells.**/
        Iterator rowIter = mySheet.rowIterator();

        int theRow = 0;
        int theadRows = 1;
        while (rowIter.hasNext()) {
            theRow++;
            HSSFRow myRow = (HSSFRow) rowIter.next();
            Iterator cellIter = myRow.cellIterator();
            //Vector cellStoreVector=new Vector();
            System.out.println("\nprinting " + theRow);
            Element tr = doc.createElement("tr");

            System.out.println("\nprinting " + theRow);
            while (cellIter.hasNext()) {
                HSSFCell myCell = (HSSFCell) cellIter.next();
                CellProperties cp = new CellProperties(myCell);

                Element td = null;
                int colspan = cp.getColspan();
                int rowspan = cp.getRowspan();
                CellReference ref = new CellReference(myCell);
                System.out.println(
                        "The value of " + ref.formatAsString() + " is " + formatter.formatCellValue(myCell));
                // String myCellValue = myCell.toString();
                //  myCell.setCellType(Cell.CELL_TYPE_STRING);
                // String myCellValue = myCell.getRichStringCellValue().toString();
                String myCellValue = formatter.formatCellValue(myCell);
                if (myCellValue != null && myCellValue.trim().endsWith(".0")) {
                    System.out.println(myCellValue + " have 0");
                    myCellValue = myCellValue.replace(".0", "");
                }
                System.out
                        .println(myCellValue + ": colspan:" + cp.getColspan() + " rowspan:" + cp.getRowspan());
                if (rowspan > 1) {
                    if (theRow == 1) {
                        theadRows = rowspan;
                    }
                }
                if (theRow <= theadRows) {
                    td = doc.createElement("th");
                    td.setAttribute("align", "left");
                } else {
                    td = doc.createElement("td");
                    td.setAttribute("align", "left");
                    td.setAttribute("valign", "top");
                }
                if (colspan > 1) {
                    td.setAttribute("colspan", colspan + "");
                }
                if (rowspan > 1) {
                    td.setAttribute("rowspan", rowspan + "");
                }
                if ((colspan > 1 || rowspan > 1) && myCellValue.trim().equals("")) {
                    continue;
                }

                Element bold = doc.createElement("bold");

                tr.appendChild(td);

                td.appendChild(doc.createTextNode(myCellValue.trim()));

                //  cellStoreVector.addElement(myCell);
            }

            if (theRow <= theadRows) {
                thead.appendChild(tr);
            } else {
                tbody.appendChild(tr);
            }
            // cellVectorHolder.addElement(cellStoreVector);
        }
    } catch (Exception e) {
        ta.append("\nerrors happen:\n");
        ta.append(e.getMessage() + "\n");
    }

    return tableFrame;
}

From source file:RefSouceOnlyMain.java

License:Creative Commons License

public static Element getTable(String name) {
    DataFormatter formatter = new DataFormatter(Locale.US);
    if (name == null) {
        DocumentBuilder db = null;
        try {/* w  ww. j  a va  2 s.co m*/
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            ta.append("\nerrors happen:\n");
            ta.append(ex.getMessage() + "\n");
        }
        doc = db.newDocument();
    }

    if (name == null) {
        name = "C:\\Users\\DLiu1\\Documents\\NetBeansProjects\\Simon\\dist\\Table 1";
    }
    String fileName = name + ".xls";

    File aaa = new File(fileName);
    if (!aaa.exists()) {
        RefSouceOnlyMain
                .error(fileName + " doesn't exist, please copy the " + fileName + " into the same folder!");
        return null;
    }
    Element tableFrame = null;
    try {

        tableFrame = doc.createElement("table");

        tableFrame.setAttribute("frame", "hsides");

        tableFrame.setAttribute("rules", "groups");
        Element thead = doc.createElement("thead");
        Element tbody = doc.createElement("tbody");
        tableFrame.appendChild(thead);
        tableFrame.appendChild(tbody);
        /** Creating Input Stream**/
        //InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
        FileInputStream myInput = new FileInputStream(aaa);

        /** Create a POIFSFileSystem object**/
        POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

        /** Create a workbook using the File System**/
        HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

        /** Get the first sheet from workbook**/
        HSSFSheet mySheet = myWorkBook.getSheetAt(0);

        /** We now need something to iterate through the cells.**/
        Iterator rowIter = mySheet.rowIterator();

        int theRow = 0;
        int theadRows = 1;
        while (rowIter.hasNext()) {
            theRow++;
            HSSFRow myRow = (HSSFRow) rowIter.next();
            Iterator cellIter = myRow.cellIterator();
            //Vector cellStoreVector=new Vector();
            System.out.println("\nprinting " + theRow);
            Element tr = doc.createElement("tr");

            System.out.println("\nprinting " + theRow);
            while (cellIter.hasNext()) {
                HSSFCell myCell = (HSSFCell) cellIter.next();
                CellProperties cp = new CellProperties(myCell);

                Element td = null;
                int colspan = cp.getColspan();
                int rowspan = cp.getRowspan();
                CellReference ref = new CellReference(myCell);
                System.out.println(
                        "The value of " + ref.formatAsString() + " is " + formatter.formatCellValue(myCell));
                // String myCellValue = myCell.toString();
                //  myCell.setCellType(Cell.CELL_TYPE_STRING);
                // String myCellValue = myCell.getRichStringCellValue().toString();
                String myCellValue = formatter.formatCellValue(myCell);
                if (myCellValue != null && myCellValue.trim().endsWith(".0")) {
                    System.out.println(myCellValue + " have 0");
                    myCellValue = myCellValue.replace(".0", "");
                }
                System.out
                        .println(myCellValue + ": colspan:" + cp.getColspan() + " rowspan:" + cp.getRowspan());
                if (rowspan > 1) {
                    if (theRow == 1) {
                        theadRows = rowspan;
                    }
                }
                if (theRow <= theadRows) {
                    td = doc.createElement("th");
                    td.setAttribute("align", "left");
                } else {
                    td = doc.createElement("td");
                    td.setAttribute("align", "left");
                    td.setAttribute("valign", "top");
                }
                if (colspan > 1) {
                    td.setAttribute("colspan", colspan + "");
                }
                if (rowspan > 1) {
                    td.setAttribute("rowspan", rowspan + "");
                }
                if ((colspan > 1 || rowspan > 1) && myCellValue.trim().equals("")) {
                    continue;
                }

                Element bold = doc.createElement("bold");

                tr.appendChild(td);

                td.appendChild(doc.createTextNode(myCellValue.trim()));

                //  cellStoreVector.addElement(myCell);
            }

            if (theRow <= theadRows) {
                thead.appendChild(tr);
            } else {
                tbody.appendChild(tr);
            }
            // cellVectorHolder.addElement(cellStoreVector);
        }
    } catch (Exception e) {
        ta.append("\nerrors happen:\n");
        ta.append(e.getMessage() + "\n");
    }

    return tableFrame;
}

From source file:CellStyleDetails.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        throw new IllegalArgumentException("Filename must be given");
    }/*ww w  .j  a  va2  s  . c o m*/

    Workbook wb = WorkbookFactory.create(new File(args[0]));
    DataFormatter formatter = new DataFormatter();

    for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) {
        Sheet sheet = wb.getSheetAt(sn);
        System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());

        for (Row row : sheet) {
            System.out.println("  Row " + row.getRowNum());

            for (Cell cell : row) {
                CellReference ref = new CellReference(cell);
                System.out.print("    " + ref.formatAsString());
                System.out.print(" (" + cell.getColumnIndex() + ") ");

                CellStyle style = cell.getCellStyle();
                System.out.print("Format=" + style.getDataFormatString() + " ");
                System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
                System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");

                Font font = wb.getFontAt(style.getFontIndex());
                System.out.print("Font=" + font.getFontName() + " ");
                System.out.print("FontColor=");
                if (font instanceof HSSFFont) {
                    System.out.print(renderColor(((HSSFFont) font).getHSSFColor((HSSFWorkbook) wb)));
                }
                if (font instanceof XSSFFont) {
                    System.out.print(renderColor(((XSSFFont) font).getXSSFColor()));
                }

                System.out.println();
                System.out.println("        " + formatter.formatCellValue(cell));
            }
        }

        System.out.println();
    }
}

From source file:com.adobe.acs.commons.data.Variant.java

License:Apache License

private void setValue(Cell cell) {
    int cellType = cell.getCellType();
    if (cellType == Cell.CELL_TYPE_FORMULA) {
        cellType = cell.getCachedFormulaResultType();
    }/*from   w ww.  j  a  va 2s. c  om*/
    switch (cellType) {
    case Cell.CELL_TYPE_BOOLEAN:
        setValue(cell.getBooleanCellValue());
        break;
    case Cell.CELL_TYPE_NUMERIC:
        double number = cell.getNumericCellValue();
        if (Math.floor(number) == number) {
            setValue((long) number);
        } else {
            setValue(number);
        }
        if (DateUtil.isCellDateFormatted(cell)) {
            setValue(cell.getDateCellValue());
        }
        DataFormatter dataFormatter = new DataFormatter();
        if (cellType == Cell.CELL_TYPE_FORMULA) {
            setValue(dataFormatter.formatCellValue(cell));
        } else {
            CellStyle cellStyle = cell.getCellStyle();
            setValue(dataFormatter.formatRawCellContents(cell.getNumericCellValue(), cellStyle.getDataFormat(),
                    cellStyle.getDataFormatString()));
        }
        break;
    case Cell.CELL_TYPE_STRING:
        setValue(cell.getStringCellValue().trim());
        break;
    case Cell.CELL_TYPE_BLANK:
    default:
        clear();
        break;
    }
}

From source file:com.assentisk.controller.OrganizationController.java

private ModelAndView importEmploye(HttpServletRequest req, HttpServletResponse res) throws Exception {
    System.out.println("hiiii heree.......");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
    MultipartFile multipartFile = multipartRequest.getFile("myexcel");
    String fileName = multipartFile.getOriginalFilename();
    map = new ModelMap();
    String name = req.getParameter("fileName");
    int status = 0;
    java.util.Date dt = new java.util.Date();
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String currentTime = sdf.format(dt);

    InetAddress ip = InetAddress.getLocalHost();
    String userId = (String) req.getSession().getAttribute("UserRecordID");

    byte[] b = multipartFile.getBytes();
    FileOutputStream fout = new FileOutputStream(new File(fileName));
    fout.write(b);//from w  w  w.j a v a2  s  .  c  om
    fout.flush();
    fout.close();
    try {
        String DepartmentID = "", LocationID = "", EmpName = "", Email1 = "", Email2 = "", address = "";
        String city = "", zip = "", phone1 = "", locCoun = "", locstate = "", loccity = "", locContact = "",
                locEmail = "";
        String phone2 = "", divisions = "", email2 = "", username = "", reporting = "", photo = "";
        int isLicense = 0;
        int isactive = 1;
        int count = 0;
        int notcount = 0;
        FileInputStream file = new FileInputStream(new File(fileName));
        boolean flag = false;
        String[] data = null;
        List<String> dataStatus = new ArrayList<String>();
        int val = 0;
        //Reading .xls files

        if (fileName.toLowerCase().endsWith(".xls")) {
            // Get the workbook instance for XLS file
            HSSFWorkbook workbook = new HSSFWorkbook(file);
            // Get first sheet from the workbook
            HSSFSheet sheet = workbook.getSheetAt(0);
            sheet.setColumnHidden((short) 14, false);
            // Iterate through each rows from first sheet
            Iterator<Row> rowIterator = sheet.rowIterator();

            if (rowIterator.hasNext()) {

                while (rowIterator.hasNext()) {
                    short cellIndex = 0;
                    HSSFRow hsrow = (HSSFRow) rowIterator.next();
                    if (hsrow.getRowNum() != 0) {
                        if (hsrow instanceof HSSFRow) {
                            try {
                                EmpName = hsrow.getCell((short) 0).getStringCellValue();

                            } catch (Exception e) {
                                EmpName = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": EmpName - "
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": EmpName - "
                                        + e.getMessage());
                                val++;
                            }
                            try {
                                DepartmentID = hsrow.getCell((short) 1).getStringCellValue();
                            } catch (Exception e) {
                                DepartmentID = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum()
                                        + ":  Department - " + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Department - "
                                        + e.getMessage());
                                val++;
                            }
                            try {
                                LocationID = hsrow.getCell((short) 2).getStringCellValue();
                            } catch (Exception e) {
                                LocationID = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": Location -"
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Location - "
                                        + e.getMessage());
                                val++;

                            }

                            try {
                                locCoun = hsrow.getCell((short) 3).getStringCellValue();
                            } catch (Exception e) {
                                locCoun = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum()
                                        + ": location Country - " + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum()
                                        + ": Location Country- " + e.getMessage());
                                val++;
                            }

                            try {
                                locstate = hsrow.getCell((short) 4).getStringCellValue();
                            } catch (Exception e) {
                                locstate = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum()
                                        + ": location State - " + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Location State- "
                                        + e.getMessage());
                                val++;
                            }

                            try {
                                loccity = hsrow.getCell((short) 5).getStringCellValue();
                            } catch (Exception e) {
                                loccity = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum()
                                        + ": location City -" + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Location City- "
                                        + e.getMessage());
                                val++;
                            }
                            try {
                                locContact = hsrow.getCell((short) 6).getStringCellValue();
                            } catch (Exception e) {
                                locContact = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum()
                                        + ": location Contact Name -" + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum()
                                        + ": Location Contact Name- " + e.getMessage());
                                val++;
                            }

                            try {
                                locEmail = hsrow.getCell((short) 7).getStringCellValue();
                                boolean isValid = false;
                                try {
                                    //
                                    // Create InternetAddress object and validated the supplied
                                    // address which is this case is an email address.
                                    InternetAddress internetAddress = new InternetAddress(locEmail);
                                    internetAddress.validate();
                                    isValid = true;
                                } catch (AddressException e) {
                                    dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum()
                                            + ": Location Email- " + e.getMessage());
                                }
                            } catch (Exception e) {
                                locEmail = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum()
                                        + ": location Email -" + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Location Email- "
                                        + e.getMessage());
                                val++;
                            }

                            try {
                                divisions = hsrow.getCell((short) 8).getStringCellValue();
                            } catch (Exception e) {
                                divisions = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": Divisions - "
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Divisions - "
                                        + e.getMessage());
                                val++;
                            }
                            try {
                                address = hsrow.getCell((short) 9).getStringCellValue();
                            } catch (Exception e) {
                                address = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": address - "
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": address - "
                                        + e.getMessage());
                                val++;
                            }
                            try {
                                city = hsrow.getCell((short) 10).getStringCellValue();
                            } catch (Exception e) {
                                city = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": city - "
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": city - "
                                        + e.getMessage());
                                val++;
                            }

                            try {

                                zip = String.valueOf(hsrow.getCell((short) 11).getNumericCellValue());
                                zip = String.valueOf(zip).split("\\.")[0];

                            } catch (Exception e) {
                                zip = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": zip - "
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": zip - "
                                        + e.getMessage());
                                val++;
                            }

                            try {

                                DataFormatter formatter = new DataFormatter();

                                phone1 = String.valueOf(hsrow.getCell((short) 12).getNumericCellValue());
                                String df2 = formatter.formatCellValue(hsrow.getCell((short) 12));
                                phone1 = df2;
                                phone1 = String.valueOf(phone1).split("\\.")[0];

                            } catch (Exception e) {
                                phone1 = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": phone1 - "
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": phone1 - "
                                        + e.getMessage());
                                val++;
                            }
                            try {
                                DataFormatter formatter = new DataFormatter();
                                phone2 = String.valueOf(hsrow.getCell((short) 13).getNumericCellValue());
                                String df2 = formatter.formatCellValue(hsrow.getCell((short) 13));
                                phone2 = df2;
                                System.out.println("check phone1" + phone2);
                                phone2 = String.valueOf(phone2).split("\\.")[0];

                            } catch (Exception e) {
                                phone2 = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": phone2 -"
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": phone2 - "
                                        + e.getMessage());
                                val++;
                            }
                            try {
                                boolean isValid = false;
                                Email1 = hsrow.getCell((short) 14).getStringCellValue();
                                try {
                                    InternetAddress internetAddress = new InternetAddress(Email1);
                                    internetAddress.validate();
                                    isValid = true;
                                } catch (AddressException e) {
                                    dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Email1 - "
                                            + e.getMessage());
                                }
                            } catch (Exception e) {
                                Email1 = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": Email1 - "
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Email1 - "
                                        + e.getMessage());
                                val++;
                            }
                            try {

                                boolean isValid = false;
                                Email2 = hsrow.getCell((short) 15).getStringCellValue();
                                try {
                                    InternetAddress internetAddress = new InternetAddress(Email2);
                                    internetAddress.validate();
                                    isValid = true;
                                } catch (AddressException e) {
                                    dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Email2 - "
                                            + e.getMessage());
                                }
                            } catch (Exception e) {
                                Email2 = "";
                                System.out.println("Wrong Data in  Row " + hsrow.getRowNum() + ": Email2 - "
                                        + e.getMessage());
                                dataStatus.add("Wrong Data in  Row " + hsrow.getRowNum() + ": Email2 - "
                                        + e.getMessage());
                                val++;
                            }

                            int userdata = 0;

                            String groupdata = "";

                            if (username.equals("")) {
                                userdata = 0;
                                reporting = "0";
                                groupdata = "0";
                            }

                            if (!LocationID.equals("")) {
                                LocationID = organizationDao.getLocIdByName(LocationID, currentTime,
                                        Integer.parseInt(userId), locCoun, locstate, loccity, locContact,
                                        locEmail);
                                if (LocationID.equals("0")) {
                                    LocationID = "";
                                }
                            }
                            if (!DepartmentID.equals("")) {
                                DepartmentID = organizationDao.getDeparmentIdByName(DepartmentID, currentTime,
                                        Integer.parseInt(userId));
                                if (DepartmentID.equals("0")) {
                                    DepartmentID = "";
                                }
                            }
                            if (!divisions.equals("")) {

                                divisions = organizationDao.getDivisionByName(divisions, currentTime,
                                        Integer.parseInt(userId));
                                if (divisions.equals("0")) {
                                    divisions = "";
                                }
                            }

                            if (!EmpName.equals("") && !DepartmentID.equals("") && !divisions.equals("")
                                    && !LocationID.equals("")) {
                                String duplicate = "";
                                try {
                                    duplicate = organizationDao.saveEmployeedata(0, DepartmentID, LocationID,
                                            EmpName, Email1, reporting, groupdata, currentTime, currentTime,
                                            Integer.parseInt(userId), currentTime, Integer.parseInt(userId),
                                            status, address, city, "", "", zip, photo, phone1, phone2,
                                            divisions, Email2);
                                    masterDao.userAuditTrail("assentisk_employees", "1", "add", currentTime,
                                            Integer.parseInt(userId), ip.getHostAddress());
                                } catch (Exception e) {
                                    //dataStatus.add("Error on the data : "+hsrow.getRowNum());

                                    req.setAttribute("message", "Invalid Data File");
                                    return new ModelAndView("organization/employees", map);
                                }

                                if (duplicate.equals("true")) {
                                    notcount = notcount + 1;
                                    dataStatus.add("Duplicate Row : " + hsrow.getRowNum());
                                } else {
                                    count = count + 1;
                                }
                            } else {
                                System.out.println(
                                        "Error Row : " + hsrow.getRowNum() + "Not Inserted Row  : " + EmpName);
                                notcount = notcount + 1;
                            }
                        }
                    }

                }
            } else {
                dataStatus.add("Please import valid Data file");
            }
            if (count > 0) {
                dataStatus.add("Succesfully inserted Row : " + count);
                val++;
            }
            if (notcount > 0) {
                if (notcount == 1) {
                    dataStatus.add(notcount + " Row is not inserted");
                } else {
                    dataStatus.add(notcount + " Rows are not inserted");
                }

            }

        } //Reading .xlsx files
        else if (fileName.toLowerCase().endsWith(".xlsx")) {

            // Get the workbook instance for XLS file
            XSSFWorkbook wBook = new XSSFWorkbook(file);
            // Get first sheet from the workbook
            XSSFSheet sheet = wBook.getSheetAt(0);
            sheet.setColumnHidden((short) 14, false);
            // Iterate through each rows from first sheet
            Iterator<Row> rowIterator = sheet.rowIterator();

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Iterator<Cell> cite = row.cellIterator();
                if (row.getRowNum() != 0) {
                    while (cite.hasNext()) {
                        Cell c = cite.next();
                        if (c.getColumnIndex() == 0) {
                            try {
                                EmpName = c.toString();
                            } catch (Exception e) {
                                EmpName = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": EmpName - "
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 1) {
                            try {
                                DepartmentID = c.toString();
                            } catch (Exception e) {
                                DepartmentID = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext()
                                        + ":  Department - " + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 2) {
                            try {
                                LocationID = c.toString();
                            } catch (Exception e) {
                                LocationID = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": Location -"
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 3) {
                            try {
                                locCoun = c.toString();
                            } catch (Exception e) {
                                locCoun = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext()
                                        + ": location Country - " + e.getMessage());

                            }
                        }
                        if (c.getColumnIndex() == 4) {
                            try {
                                locstate = c.toString();
                            } catch (Exception e) {
                                locstate = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext()
                                        + ": location State - " + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 5) {
                            try {
                                loccity = c.toString();
                            } catch (Exception e) {
                                loccity = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext()
                                        + ": location City -" + e.getMessage());

                            }
                        }
                        if (c.getColumnIndex() == 6) {
                            try {
                                locContact = c.toString();
                            } catch (Exception e) {
                                locContact = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext()
                                        + ": location Contact Name -" + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 7) {
                            try {
                                locEmail = c.toString();
                                boolean isValid = false;
                                try {
                                    InternetAddress internetAddress = new InternetAddress(locEmail);
                                    internetAddress.validate();
                                    isValid = true;
                                } catch (AddressException e) {
                                    dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext()
                                            + ": locEmail - " + e.getMessage());
                                }

                            } catch (Exception e) {
                                locEmail = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext()
                                        + ": location Email -" + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 8) {
                            try {
                                divisions = c.toString();
                            } catch (Exception e) {
                                divisions = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": Divisions - "
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 9) {
                            try {
                                address = c.toString();
                            } catch (Exception e) {
                                address = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": address - "
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 10) {
                            try {
                                city = c.toString();
                            } catch (Exception e) {
                                city = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": city - "
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 11) {
                            try {
                                zip = c.toString();
                            } catch (Exception e) {
                                zip = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": zip - "
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 12) {
                            try {
                                DataFormatter formatter = new DataFormatter();
                                phone1 = c.toString();
                                String df2 = formatter.formatCellValue(row.getCell((short) 12));
                                phone1 = df2;
                            } catch (Exception e) {
                                phone1 = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": phone1 - "
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 13) {
                            try {
                                DataFormatter formatter = new DataFormatter();
                                phone2 = c.toString();
                                String df2 = formatter.formatCellValue(row.getCell((short) 12));
                                phone2 = df2;
                            } catch (Exception e) {
                                phone2 = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": phone2 -"
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 3) {
                            try {
                                Email1 = c.toString();
                                boolean isValid = false;
                                try {
                                    InternetAddress internetAddress = new InternetAddress(Email1);
                                    internetAddress.validate();
                                    isValid = true;
                                } catch (AddressException e) {
                                    dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": Email1 - "
                                            + e.getMessage());
                                }
                            } catch (Exception e) {
                                Email1 = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": Email1 - "
                                        + e.getMessage());
                            }
                        }
                        if (c.getColumnIndex() == 10) {
                            try {
                                Email2 = c.toString();
                                boolean isValid = false;
                                try {
                                    InternetAddress internetAddress = new InternetAddress(Email2);
                                    internetAddress.validate();
                                    isValid = true;
                                } catch (AddressException e) {
                                    dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": Email2 - "
                                            + e.getMessage());
                                }
                            } catch (Exception e) {
                                Email2 = "";
                                dataStatus.add("Wrong Data in  Row " + rowIterator.hasNext() + ": Email2 - "
                                        + e.getMessage());
                            }
                        }

                    }

                    int userdata = 0;

                    String groupdata = "";

                    if (username.equals("")) {
                        userdata = 0;
                        reporting = "0";
                        groupdata = "0";
                    }

                    if (!LocationID.equals("")) {
                        LocationID = organizationDao.getLocIdByName(LocationID, currentTime,
                                Integer.parseInt(userId), locCoun, locstate, loccity, locContact, locEmail);
                        if (LocationID.equals("0")) {
                            LocationID = "";
                        }
                    }
                    if (!DepartmentID.equals("")) {
                        DepartmentID = organizationDao.getDeparmentIdByName(DepartmentID, currentTime,
                                Integer.parseInt(userId));
                        if (DepartmentID.equals("0")) {
                            DepartmentID = "";
                        }
                    }
                    if (!divisions.equals("")) {

                        divisions = organizationDao.getDivisionByName(divisions, currentTime,
                                Integer.parseInt(userId));
                        if (divisions.equals("0")) {
                            divisions = "";
                        }
                    }

                    if (!EmpName.equals("") && !DepartmentID.equals("") && !divisions.equals("")
                            && !LocationID.equals("")) {
                        String duplicate = "";
                        try {
                            duplicate = organizationDao.saveEmployeedata(0, DepartmentID, LocationID, EmpName,
                                    Email1, reporting, groupdata, currentTime, currentTime,
                                    Integer.parseInt(userId), currentTime, Integer.parseInt(userId), status,
                                    address, city, "", "", zip, photo, phone1, phone2, divisions, Email2);
                            masterDao.userAuditTrail("assentisk_employees", "1", "add", currentTime,
                                    Integer.parseInt(userId), ip.getHostAddress());

                        } catch (Exception e) {
                            //dataStatus.add("Error on the data : "+hsrow.getRowNum());
                            req.setAttribute("message", "Invalid Data File");

                            return new ModelAndView("organization/employees", map);
                        }

                        if (duplicate.equals("true")) {
                            notcount = notcount + 1;
                            dataStatus.add("Duplicate Row : " + row.getRowNum());
                        } else {
                            count = count + 1;
                        }
                    } else {
                        System.out.println(
                                "Error Row : " + row.getRowNum() + "Not Inserted Row EmpName : " + EmpName);
                        notcount = notcount + 1;
                    }
                }
            }

            if (count > 0) {
                System.out.println("Succesfully inserted Row :" + count);
                dataStatus.add("Succesfully inserted Row : " + count);
                val++;
            }
            if (notcount > 0) {
                dataStatus.add(notcount + " Rows are not inserted");
            }

            file.close();

            File f = new File(fileName);

            if (f.exists()) {
                f.delete();
            }
        }

        if (dataStatus.size() > 0) {
            map.addObject("dataStatus", dataStatus);
            map.addObject("datasize", "true");

        } else {
            map.addObject("datasize", "false");
        }
        file.close();
        File f = new File(fileName);
        if (f.exists()) {
            f.delete();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        req.setAttribute("message", "Invalid data file");
    } catch (IOException e) {
        e.printStackTrace();
        req.setAttribute("message", "Invalid data file");
    } catch (Exception e) {
        e.printStackTrace();
        req.setAttribute("message", "Invalid data file");
    }
    return new ModelAndView("organization/employees", map);
}

From source file:com.gsecs.GSECSFrame.java

private Object getCellValue(Cell cell) {
    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
        return cell.getStringCellValue();

    case Cell.CELL_TYPE_BOOLEAN:
        return cell.getBooleanCellValue();

    case Cell.CELL_TYPE_NUMERIC:
        DataFormatter df = new DataFormatter();
        String stringCellValue = df.formatCellValue(cell);
        return stringCellValue;
    }//from www . j  a  v a 2s  . c om

    return null;
}

From source file:com.openitech.db.model.ExcelDataSource.java

License:Apache License

@Override
public boolean loadData(boolean reload, int oldRow) {
    boolean result = false;

    if (isDataLoaded && !reload) {
        return false;
    }/*from   w  w w .  j av  a  2 s .c o m*/
    if (sourceFile != null) {
        try {
            Workbook workBook = WorkbookFactory.create(new FileInputStream(sourceFile));
            //        HSSFWorkbook workBook = new HSSFWorkbook(new FileInputStream(sourceFile));
            Sheet sheet = workBook.getSheetAt(0);
            DataFormatter dataFormatter = new DataFormatter(Locale.GERMANY);
            FormulaEvaluator formulaEvaluator = workBook.getCreationHelper().createFormulaEvaluator();

            int lastRowNum = sheet.getLastRowNum();

            boolean isFirstLineHeader = true;

            //count = sheet. - (isFirstLineHeader ? 1 : 0);
            int tempCount = 0;
            for (int j = 0; j <= lastRowNum; j++) {
                //zane se z 0
                Row row = row = sheet.getRow(j);
                if (row == null) {
                    continue;
                }

                // display row number in the console.
                System.out.println("Row No.: " + row.getRowNum());
                if (isFirstLineHeader && row.getRowNum() == 0) {
                    populateHeaders(row);
                    continue;
                }
                tempCount++;

                Map<String, DataColumn> values;
                if (rowValues.containsKey(row.getRowNum())) {
                    values = rowValues.get(row.getRowNum());
                } else {
                    values = new HashMap<String, DataColumn>();
                    rowValues.put(row.getRowNum(), values);
                }

                // once get a row its time to iterate through cells.
                int lastCellNum = row.getLastCellNum();
                for (int i = 0; i <= lastCellNum; i++) {
                    DataColumn dataColumn = new DataColumn();
                    Cell cell = row.getCell(i);
                    if (cell == null) {
                        continue;
                    }
                    System.out.println("Cell No.: " + cell.getColumnIndex());
                    System.out.println("Value: " + dataFormatter.formatCellValue(cell));
                    if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                        dataColumn = new DataColumn(dataFormatter.formatCellValue(cell, formulaEvaluator));
                    } else {
                        dataColumn = new DataColumn(dataFormatter.formatCellValue(cell));
                    }

                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC: {
                        // cell type numeric.
                        System.out.println("Numeric value: " + cell.getNumericCellValue());
                        dataColumn = new DataColumn(dataFormatter.formatCellValue(cell));
                        break;
                    }
                    case Cell.CELL_TYPE_STRING:
                        // cell type string.
                        System.out.println("String value: " + cell.getStringCellValue());
                        dataColumn = new DataColumn(dataFormatter.formatCellValue(cell));
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        // cell type string.
                        System.out.println("String value: " + cell.getBooleanCellValue());
                        dataColumn.setValue(cell.getBooleanCellValue(), Boolean.class);
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        // cell type string.
                        System.out.println(
                                "Formula value: " + dataFormatter.formatCellValue(cell, formulaEvaluator));
                        dataColumn = new DataColumn(dataFormatter.formatCellValue(cell, formulaEvaluator));
                        break;
                    default:
                        dataColumn.setValue(cell.getStringCellValue(), String.class);
                        break;
                    }

                    values.put(getColumnName(cell.getColumnIndex()).toUpperCase(), dataColumn);

                }
            }

            count = tempCount;

            isDataLoaded = true;
            //se postavim na staro vrstico ali 1
            if (oldRow > 0) {
                absolute(oldRow);
            } else {
                first();
            }

            result = true;
        } catch (Exception ex) {
            Logger.getLogger(ExcelDataSource.class.getName()).log(Level.SEVERE, null, ex);
            result = false;
        }
    }

    return result;
}

From source file:com.simopuve.helper.ReadPVDFromFile.java

private static String getTextFromCell(Integer rowX, Integer cellY, DataFormatter formatter, Sheet sheet,
        Row row) {//from w  ww  .ja  va2  s .  co m
    Row rowL = (row == null) ? sheet.getRow(rowX) : row;
    Cell cell = rowL.getCell(cellY);
    return formatter.formatCellValue(cell);
}

From source file:com.stam.excellatin.ExcelLatin.java

public static void main(String[] args) {
    List<String> options = new ArrayList<>();
    int startIndex = 0;
    for (String arg : args) {
        if (validOptions.contains(arg)) {
            options.add(arg);/*  ww  w. j  a  v  a  2  s . c  om*/
            startIndex++;
        }
    }

    if (args[0].equals("-h") || args.length < 3) {
        System.out.println("usage: ExcelLatin [options] filenameIn filenameOut columnNames...");
        System.out.println("options:");
        System.out.println("\t-L\tto Latin (default)");
        System.out.println("\t-G\tto Greek");
        System.out.println("\t-d\tdon't deaccent");
        System.out.println("\t-h\thelp");
    } else {
        boolean greekToLatin = false;
        boolean latinToGreek = false;
        Transliterator transliterator = null;
        if ((!options.contains("-L") && !options.contains("-G")) || options.contains("-L")) {
            transliterator = Transliterator.getInstance("Greek-Latin/UNGEGN");
            System.out.println("\nTransliterating Greek to Latin");
            greekToLatin = true;
        } else if (options.contains("-G")) {
            transliterator = Transliterator.getInstance("Latin-Greek/UNGEGN");
            System.out.println("\nTransliterating Latin to Greek");
            latinToGreek = true;
        }

        if (transliterator == null) {
            System.out.println("Not a valid option for the transliteration language");
            return;
        }

        boolean deAccent = true;
        if (options.contains("-d")) {
            deAccent = false;
            System.out.println("Will not deaccent");
        }

        String fileNameIn = args[startIndex];
        String fileNameOut = args[startIndex + 1];
        List<String> columnNames = new ArrayList<>();
        System.out.println("\nColumns to transliterate\n---------------------------");
        for (int i = startIndex + 2; i < args.length; i++) {
            columnNames.add(args[i]);
            System.out.println(args[i]);
        }
        System.out.println("\n");

        try {
            File file = new File(fileNameIn);
            if (!file.exists()) {
                System.out.println("The file " + fileNameIn + " was not found");
                return;
            }

            Map<String, String> mapTransformations = new HashMap<>();
            Scanner sc = new Scanner(new FileReader("map.txt"));
            while (sc.hasNextLine()) {
                String greekEntry = sc.next();
                String latinEntry = sc.next();

                if (greekToLatin) {
                    mapTransformations.put(greekEntry, latinEntry);
                } else if (latinToGreek) {
                    mapTransformations.put(latinEntry, greekEntry);
                }
            }

            DataFormatter formatter = new DataFormatter();
            Workbook wb = WorkbookFactory.create(file);

            Workbook newWb = null;
            if (wb instanceof HSSFWorkbook) {
                newWb = new HSSFWorkbook();
            } else if (wb instanceof XSSFWorkbook) {
                newWb = new XSSFWorkbook();
            }
            FileOutputStream fileOut = new FileOutputStream(fileNameOut);
            if (newWb != null) {
                Sheet sheetOut = newWb.createSheet();

                Sheet sheet = wb.getSheetAt(0);

                List<Integer> idxs = new ArrayList<>();

                Row row = sheet.getRow(0);
                for (Cell cell : row) {
                    String cellVal = formatter.formatCellValue(cell);
                    if (cellVal == null || cellVal.trim().equals("")) {
                        break;
                    }

                    if (columnNames.contains(cell.getStringCellValue())) {
                        idxs.add(cell.getColumnIndex());
                    }
                }

                for (Row rowIn : sheet) {
                    Row rowOut = sheetOut.createRow(rowIn.getRowNum());
                    if (rowIn.getRowNum() == 0) {
                        for (Cell cell : rowIn) {
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            Cell cellOut = rowOut.createCell(cell.getColumnIndex());
                            cellOut.setCellValue(cell.getStringCellValue());
                        }
                    } else {
                        for (Cell cell : rowIn) {
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            String cellVal = formatter.formatCellValue(cell);
                            String cellNewVal = cellVal;
                            if (idxs.contains(cell.getColumnIndex()) && cellVal != null) {
                                if (mapTransformations.containsKey(cellVal)) {
                                    cellNewVal = mapTransformations.get(cellVal);
                                } else {
                                    if (deAccent) {
                                        cellNewVal = deAccent(transliterator.transform(cellVal));
                                    } else {
                                        cellNewVal = transliterator.transform(cellVal);
                                    }
                                }
                            }
                            Cell cellOut = rowOut.createCell(cell.getColumnIndex());
                            cellOut.setCellValue(cellNewVal);
                        }
                    }
                }

                System.out.println("Finished!");

                newWb.write(fileOut);
                fileOut.close();
            }
        } catch (IOException | InvalidFormatException ex) {
            Logger.getLogger(ExcelLatin.class.toString()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:de.tum.in.socket.server.ReadExcel.java

License:Apache License

/**
 * Returns the type of value from a cell
 *///from w w  w.  j  a  v a 2s. c om
private static Object getTypeValue(final Class<?> type, final Cell cell) {
    Object typedValue = null;
    final DataFormatter formatter = new DataFormatter();
    if (type == int.class) {
        typedValue = (int) cell.getNumericCellValue();
    } else if (type == double.class) {
        typedValue = cell.getNumericCellValue();
    } else if (type == boolean.class) {
        typedValue = cell.getBooleanCellValue();
    } else if (type == String.class) {
        typedValue = formatter.formatCellValue(cell);
    }
    return typedValue;
}