Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook HSSFWorkbook

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook HSSFWorkbook

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFWorkbook HSSFWorkbook.

Prototype

public HSSFWorkbook(InputStream s) throws IOException 

Source Link

Document

Companion to HSSFWorkbook(POIFSFileSystem), this constructs the POI filesystem around your InputStream , including all nodes.

Usage

From source file:com.afrisoftech.lib.ExportData.java

public static Vector read(String fileName) {
    Vector cellVectorHolder = new Vector();
    try {/* w ww.ja  v a 2 s .c  o  m*/

        FileInputStream myInput = new FileInputStream(fileName);
        POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
        HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
        HSSFSheet mySheet = myWorkBook.getSheetAt(0);
        Iterator rowIter = mySheet.rowIterator();
        while (rowIter.hasNext()) {
            HSSFRow myRow = (HSSFRow) rowIter.next();
            Iterator cellIter = myRow.cellIterator();
            Vector cellStoreVector = new Vector();
            while (cellIter.hasNext()) {
                HSSFCell myCell = (HSSFCell) cellIter.next();
                //Object obj=myCell.getStringCellValue();
                System.out.print(myCell.getCellType() + " -");
                if (myCell.getCellType() == 0) {
                    cellStoreVector.addElement(myCell.getNumericCellValue());

                } else if (myCell.getCellType() == 1) {
                    cellStoreVector.addElement(myCell.getStringCellValue());

                }
                //cellStoreVector.addElement(myCell.getStringCellValue());
            }
            System.out.println();
            cellVectorHolder.addElement(cellStoreVector);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return cellVectorHolder;
}

From source file:com.alkacon.opencms.excelimport.CmsExcelContent.java

License:Open Source License

/**
 * Reads the excel file row by row. Fills the excel import internal structure which is column wise.<p>
 * /*from w w  w.j  a v a2s. c o m*/
 * @param in the document input stream
 * 
 * @throws IOException if something goes wring
 */
private void readExcelColumnContents(InputStream in) throws IOException {

    HSSFWorkbook excelWb = new HSSFWorkbook(in);
    HSSFSheet sheet = excelWb.getSheetAt(0);
    int rowsNumber = sheet.getPhysicalNumberOfRows();
    if (rowsNumber > 0) {

        // loop over all rows from excel
        // do not read first column, because here are only user raw names
        for (int rowCounter = 1; rowCounter < sheet.getPhysicalNumberOfRows(); rowCounter++) {
            HSSFRow row = sheet.getRow(rowCounter);

            if ((row != null)) {
                // get number of rows in excel
                if ((rowCounter) > m_rowNumber) {
                    m_rowNumber = rowCounter;
                }
                // loop over all columns in this row
                for (int columnCounter = 0; columnCounter < row.getLastCellNum(); columnCounter++) {
                    CmsExcelColumn cmsExcelCol = (CmsExcelColumn) m_colContents.get(new Integer(columnCounter));
                    if (cmsExcelCol != null) {
                        // read cell
                        HSSFCell cell = row.getCell((short) columnCounter);
                        if (cell != null) {
                            String text = null;
                            try {
                                // read cell content from excel
                                switch (cell.getCellType()) {
                                case Cell.CELL_TYPE_BLANK:
                                case Cell.CELL_TYPE_ERROR:
                                    // ignore all blank or error cells
                                    break;
                                case Cell.CELL_TYPE_NUMERIC:
                                    // check for date
                                    if (DateUtil.isCellDateFormatted(cell)
                                            || DateUtil.isValidExcelDate(cell.getNumericCellValue())) {
                                        // valid date
                                        Date date = DateUtil.getJavaDate(cell.getNumericCellValue());
                                        text = new Long(date.getTime()).toString();
                                    } else {
                                        // no valid date
                                        text = Double.toString(cell.getNumericCellValue());
                                    }
                                    break;
                                case Cell.CELL_TYPE_BOOLEAN:
                                    text = Boolean.toString(cell.getBooleanCellValue());
                                    break;
                                case Cell.CELL_TYPE_STRING:
                                default:
                                    text = cell.getStringCellValue();
                                    break;
                                }
                                // add to column list
                                cmsExcelCol.addNewCellValue(rowCounter, text);
                                m_colContents.put(new Integer(columnCounter), cmsExcelCol);
                            } catch (Exception e) {
                                if (LOG.isErrorEnabled()) {
                                    LOG.error(e.toString());
                                }
                            }
                        } else {
                            // add to column list
                            cmsExcelCol.addNewCellValue(rowCounter, "");
                            m_colContents.put(new Integer(columnCounter), cmsExcelCol);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.alkacon.opencms.excelimport.CmsExcelContent.java

License:Open Source License

/**
 * Creates mapping between excel column names set by user and excel column names from excel internal.<p>
 * // www  .ja v a  2 s  .c o  m
 * @param in the document input stream
 * 
 * @throws IOException if something goes wring
 */
private void readExcelColumnMappings(InputStream in) throws IOException {

    HSSFWorkbook excelWb = new HSSFWorkbook(in);
    HSSFSheet sheet = excelWb.getSheetAt(0);
    int numberOfRows = sheet.getPhysicalNumberOfRows();
    if (numberOfRows > 0) {

        HSSFRow firstRow = sheet.getRow(0);
        // loop over all columns in first excel row
        Iterator rowIter = firstRow.cellIterator();
        while (rowIter.hasNext()) {
            // get cell
            HSSFCell cell = (HSSFCell) rowIter.next();
            if (cell != null) {
                // get user column name
                String userColName = cell.getStringCellValue();
                // get excel column name
                int excelColName = cell.getCellNum();
                CmsExcelColumn excelCol = new CmsExcelColumn(userColName, excelColName);
                m_colNames.put(userColName, new Integer(excelColName));
                m_colContents.put(new Integer(excelColName), excelCol);
            }
        }
    }
}

From source file:com.allinfinance.bo.impl.risk.T40201BOTarget.java

License:Open Source License

public String importFile(List<File> fileList, List<String> fileNameList, Operator operator) throws Exception {
    HSSFWorkbook workbook = null;//ww  w  . ja v a 2 s .c o  m
    HSSFSheet sheet = null;
    HSSFRow row = null;
    // ?
    String returnMsg = "";
    // ??
    int fileNameIndex = 0;
    // ??
    String fileName = null;

    // ??
    String saCardNo = null;
    // ??
    String saLimitAmt = null;
    // ?
    String saAction = null;
    // 
    String saBrhId = operator.getOprBrhId();
    // ?
    String saOprId = operator.getOprId();
    // 
    String saInitTime = CommonFunction.getCurrentDateTime();

    TblCtlCardInf tblCtlCardInf = null;

    FileInputStream fileInputStream = null;

    for (File file : fileList) {

        fileInputStream = new FileInputStream(file);

        workbook = new HSSFWorkbook(fileInputStream);

        sheet = workbook.getSheetAt(0);

        fileName = fileNameList.get(fileNameIndex);

        for (int rowIndex = sheet.getFirstRowNum(); rowIndex <= sheet.getLastRowNum(); rowIndex++) {

            row = sheet.getRow(rowIndex);

            for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
                if (row.getCell(i).getCellType() != HSSFCell.CELL_TYPE_STRING)
                    returnMsg += "[ " + fileName + " ]" + (row.getRowNum() + 1) + "" + ""
                            + (i + 1) + "???<br>";

            if (!"".equals(returnMsg))
                return returnMsg;

            saCardNo = row.getCell(0).getStringCellValue();
            // ??
            if (saCardNo.getBytes().length > 19)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            saLimitAmt = row.getCell(1).getStringCellValue();
            //            saLimitAmt = CommonFunction.transYuanToFen(saLimitAmt);

            // ??
            if (!CommonFunction.isAllDigit(saLimitAmt))
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "????<br>";

            if (saLimitAmt.getBytes().length > 12)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            saAction = row.getCell(2).getStringCellValue();
            // ?
            if (!("1".equals(saAction) || "2".equals(saAction) || "3".equals(saAction) || "4".equals(saAction)))
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            // ???????
            tblCtlCardInf = new TblCtlCardInf();
            tblCtlCardInf.setId(saCardNo);
            tblCtlCardInf.setSaLimitAmt(saLimitAmt);
            tblCtlCardInf.setSaAction(saAction);
            tblCtlCardInf.setSaInitZoneNo(saBrhId);
            tblCtlCardInf.setSaInitOprId(saOprId);
            tblCtlCardInf.setSaInitTime(saInitTime);
            tblCtlCardInfDAO.saveOrUpdate(tblCtlCardInf);
        }
        fileInputStream.close();
        fileNameIndex++;
    }
    return Constants.SUCCESS_CODE;
}

From source file:com.allinfinance.bo.impl.risk.T40202BOTarget.java

License:Open Source License

@SuppressWarnings("unchecked")
public String importFile(List<File> fileList, List<String> fileNameList, Operator operator) throws Exception {
    HSSFWorkbook workbook = null;//from  w ww  .  j  ava  2  s .  c  o m
    HSSFSheet sheet = null;
    HSSFRow row = null;
    // ?
    String returnMsg = "";
    // ??
    int fileNameIndex = 0;
    // ??
    String fileName = null;
    String sql = null;
    // 
    List<Object[]> dataList = null;

    // ??
    String saMerNo = null;
    // ??
    String saMerChName = null;
    // ??
    String saMerEnName = null;
    // ?
    String saZoneNo = null;
    // ??
    String saLimitAmt = null;
    // ?
    String saAction = null;
    // 
    String saBrhId = operator.getOprBrhId();
    // ?
    String saOprId = operator.getOprId();
    // 
    String saInitTime = CommonFunction.getCurrentDateTime();

    TblCtlMchtInf tblCtlMchtInf = null;

    FileInputStream fileInputStream = null;

    for (File file : fileList) {

        fileInputStream = new FileInputStream(file);

        workbook = new HSSFWorkbook(fileInputStream);

        sheet = workbook.getSheetAt(0);

        fileName = fileNameList.get(fileNameIndex);

        for (int rowIndex = sheet.getFirstRowNum(); rowIndex <= sheet.getLastRowNum(); rowIndex++) {

            row = sheet.getRow(rowIndex);

            for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
                if (row.getCell(i).getCellType() != HSSFCell.CELL_TYPE_STRING)
                    returnMsg += "[ " + fileName + " ]" + (row.getRowNum() + 1) + "" + ""
                            + (i + 1) + "???<br>";

            if (!"".equals(returnMsg))
                return returnMsg;

            saMerNo = row.getCell(0).getStringCellValue();
            // ?
            if (saMerNo.getBytes().length > 15)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";
            sql = "select  mcht_nm,eng_name,bank_no from TBL_MCHT_BASE_INF where MCHT_NO = '" + saMerNo + "'";

            dataList = CommonFunction.getCommQueryDAO().findBySQLQuery(sql);
            if (dataList.size() == 0)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "??<br>";
            // ??
            saMerChName = dataList.get(0)[0].toString();
            // ??
            saMerEnName = dataList.get(0)[1].toString();
            saZoneNo = dataList.get(0)[2].toString();

            saLimitAmt = row.getCell(1).getStringCellValue();
            //            saLimitAmt = CommonFunction.transYuanToFen(saLimitAmt);

            // ??
            if (!CommonFunction.isAllDigit(saLimitAmt))
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "????<br>";

            if (saLimitAmt.getBytes().length > 12)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            saAction = row.getCell(2).getStringCellValue();
            // ?
            if (!("1".equals(saAction) || "2".equals(saAction) || "3".equals(saAction) || "4".equals(saAction)))
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            // ??????
            tblCtlMchtInf = new TblCtlMchtInf();
            tblCtlMchtInf.setId(saMerNo);
            tblCtlMchtInf.setSaMerChName(saMerChName);
            tblCtlMchtInf.setSaMerEnName(saMerEnName);
            tblCtlMchtInf.setSaZoneNo(saZoneNo);
            tblCtlMchtInf.setSaLimitAmt(saLimitAmt);
            tblCtlMchtInf.setSaAction(saAction);
            tblCtlMchtInf.setSaInitZoneNo(saBrhId);
            tblCtlMchtInf.setSaInitOprId(saOprId);
            tblCtlMchtInf.setSaInitTime(saInitTime);
            tblCtlMchtInfDAO.saveOrUpdate(tblCtlMchtInf);
        }
        fileInputStream.close();
        fileNameIndex++;
    }
    return Constants.SUCCESS_CODE;
}

From source file:com.alphacell.controller.CargarDatosBean.java

public void handleFileUpload(FileUploadEvent event) {

    if (event.getFile().equals(null)) {

        FacesUtil.addInfoMessage("El archivo es null");

    }/*from   ww  w.  java  2 s  . co m*/
    InputStream file;
    HSSFWorkbook workbook = null;
    try {
        file = event.getFile().getInputstream();
        workbook = new HSSFWorkbook(file);
    } catch (IOException e) {

        FacesUtil.addErrorMessage("Error Leyendo archivo : " + e);

    }

    HSSFSheet sheet = workbook.getSheetAt(1);

    Iterator<Row> rowIterator = sheet.iterator();
    Calendar calendar = new GregorianCalendar();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();

        Iterator<Cell> cellIterator = row.cellIterator();
        //Job job = new Job();
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();

            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:

                if (HSSFDateUtil.isCellDateFormatted(cell) || HSSFDateUtil.isCellInternalDateFormatted(cell)) {
                    calendar.setTime(cell.getDateCellValue());
                } else {
                    System.out.print(cell.getNumericCellValue() + "\t\t");
                }
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "\t\t");
                break;
            }

        }
    }
}

From source file:com.amitycoin.enterprisetool.diagramInputServlet.java

@Override
@SuppressWarnings({ "null", "ValueOfIncrementOrDecrementUsed", "UnusedAssignment" })
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String filePath;//from w  ww  . ja v  a2 s  .c  o m
    String docids;
    String userid;
    String a[][];
    a = new String[200][200];
    // database connection settings
    String dbURL = "jdbc:mysql://localhost:3306/enterprisedb";
    String dbUser = "root";
    String dbPass = "sandy";

    @SuppressWarnings("UnusedAssignment")
    Connection conn = null; // connection to the database
    userid = (String) request.getAttribute("uidM");
    String fname = (String) request.getAttribute("fnameM");
    int docid = (Integer) request.getAttribute("docidM");

    docids = "" + docid;
    String pathToWeb;
    pathToWeb = getServletContext().getRealPath(File.separator);
    System.out.println("pathtoweb:\t" + pathToWeb);
    filePath = pathToWeb + "readFiles\\";
    filePath = filePath + docids + userid + fname; //+.xls
    File myFile = new File(filePath);

    //boolean newExcel;
    //boolean oldExcel;
    String ext = FilenameUtils.getExtension(filePath);
    System.out.println("Extension: " + ext);

    FileInputStream fis = new FileInputStream(myFile);
    Workbook wb = null;
    if ("xls".equals(ext)) {
        // Finds the workbook instance for the file
        wb = new HSSFWorkbook(fis);

    } else if ("xlsx".equals(ext)) {
        wb = new XSSFWorkbook(fis);

    }

    @SuppressWarnings("null")
    Sheet mySheet;
    mySheet = wb.getSheetAt(0);

    // Get iterator to all the rows in current sheet
    Iterator<Row> rowIterator = mySheet.iterator();

    @SuppressWarnings("UnusedAssignment")
    int rowct = 0, colct = 0, colit = 0, ci = 0, ri = 0;

    // Traversing over each row of XLSX file
    while (rowIterator.hasNext()) {
        ri++;
        System.out.println("\nRi:\t" + ri);
        //Iterate over Rows
        Row row = rowIterator.next();

        if (1 == rowct) {
            colct = colit;
        }
        // For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        ci = 0;
        while (cellIterator.hasNext()) {

            ci++;

            System.out.println("\nCi:\t" + ci);
            //Iterate over Columns
            Cell cell = cellIterator.next();

            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "\t");
                a[ri][ci] = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                System.out.print(cell.getNumericCellValue() + "\t");
                double temp = cell.getNumericCellValue();
                String dblValue = "" + temp;
                a[ri][ci] = dblValue;
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.print(cell.getBooleanCellValue() + "\t");
                String tmp = "" + cell.getBooleanCellValue();
                a[ri][ci] = tmp;
                break;
            default:

            }
            colit++;

        }
        //rowit++;
        rowct++;
        //increase row count
    }

    System.out.println("Row Count:\t" + rowct);
    System.out.println("Column Count:\t" + colct);
    for (int i = 1; i <= rowct; i++) {
        for (int j = 1; j <= colct; j++) {
            System.out.println("a[" + i + "][" + j + "]=" + a[i][j] + "\n");
        }
    }
    try {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
        String append = "?, ?";
        String quest = ", ?";

        for (int j = 1; j <= colct; j++) {
            append += quest;
        }

        String crsql;
        String cappend = "`uid`,`doc_id`";
        for (int j = 1; j <= colct; j++) {
            cappend = cappend + ",`" + j + "`";
        }
        crsql = "CREATE TABLE IF NOT EXISTS `data" + userid + docid + "` (\n"
                + "`row_id` INT(11) NOT NULL AUTO_INCREMENT,\n" + "`uid` VARCHAR(50) NOT NULL,\n"
                + "`doc_id` INT(11) NOT NULL";
        System.out.println(crsql);

        for (int j = 1; j <= colct; j++) {
            System.out.println("j:\t" + (j));
            crsql = crsql + ",\n`" + (j) + "` VARCHAR(50)";
        }
        crsql += ",\nPRIMARY KEY (`row_id`)\n)";

        System.out.println(crsql);

        PreparedStatement cstmt = conn.prepareStatement(crsql);
        int c = cstmt.executeUpdate();

        String sql = "INSERT INTO data" + userid + docid + "(" + cappend + ")" + " values (" + append + ")";
        System.out.println("Append=\t" + append);
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1, userid);
        statement.setInt(2, docid);
        for (int i = 1; i <= rowct; i++) {
            for (int j = 1; j <= (colct); j++) {
                statement.setString(j + 2, a[i][j]);
                System.out.println("j=" + (j) + "\ta[" + i + "][" + (j) + "]=" + a[i][j] + "\n");
            }
            System.out.println("\n");
            System.out.println("\nstatement:\t" + statement);
            int res = statement.executeUpdate();
        }
    } catch (SQLException ex) {
        Logger.getLogger(diagramInputServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    for (int i = 1; i <= rowct; i++) {
        for (int j = 1; j <= colct; j++) {
            System.out.println("a[" + i + "][" + j + "]=" + a[i][j] + "\n");
        }
    }
    System.out.println("Rowct:\t" + rowct + "\nColct:\t" + colct);
    @SuppressWarnings("UseOfObsoleteCollectionType")
    Hashtable<String, Object> style = new Hashtable<String, Object>();
    style.put(mxConstants.STYLE_FILLCOLOR, mxUtils.getHexColorString(Color.WHITE));
    style.put(mxConstants.STYLE_STROKEWIDTH, 1.5);
    style.put(mxConstants.STYLE_STROKECOLOR, mxUtils.getHexColorString(new Color(0, 0, 170)));
    style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_ELLIPSE);
    style.put(mxConstants.STYLE_PERIMETER, mxConstants.PERIMETER_ELLIPSE);

    graph = new mxGraph();

    mxStylesheet stylesheet = graph.getStylesheet();
    stylesheet.putCellStyle("process", createProcessStyle());
    stylesheet.putCellStyle("object", createObjectStyle());
    stylesheet.putCellStyle("state", createStateStyle());
    stylesheet.putCellStyle("agent", createAgentLinkStyle());
    fr = new JFrame("Enterprise Architecture Diagram");

    fr.setSize(2000, 2000);
    graph.setMinimumGraphSize(new mxRectangle(0, 0, 1000, 1500));
    graph.setMaximumGraphBounds(new mxRectangle(0, 0, 2000, 2000));
    graph.setMinimumGraphSize(new mxRectangle(0, 0, 1000, 1000));

    double rech1 = 200;
    double rech2 = 200;
    double rech3 = 170;
    double rech3e = 180;
    double rech4 = 120;
    Object defaultParent = graph.getDefaultParent();

    graph.setConstrainChildren(true);
    graph.setExtendParents(true);
    graph.setExtendParentsOnAdd(true);
    graph.setDefaultOverlap(0);
    graph.setCellsMovable(true); // Moving cells in the graph. Note that an edge is also a cell.
    graph.setCellsEditable(true);
    graph.setCellsResizable(true); // Inhibit cell re-sizing.

    graph.getModel().beginUpdate();

    Object[] obj = new Object[100];
    int k = 1;
    for (int i = 2; i <= rowct; i++) {
        for (int j = 1; j <= 2; j++) {
            obj[k] = a[i][j];
            k++;
        }

    }

    //print debug info
    for (int l = 1; l <= (rowct * 2) - 2; l++) {
        System.out.println("obj[" + l + "]:\t" + obj[l]);
    }

    List<Object> list = new ArrayList<Object>();
    for (Object val : obj) {
        if (!list.contains(val)) {
            list.add(val);
        }
    }

    list.remove(null);
    list.toArray(new Object[0]);
    System.out.println("list:" + list);

    Object[] array = new Object[list.size()];
    list.toArray(array); // fill the array
    System.out.println("Array:\t" + Arrays.toString(array));

    Object[] gArray = new Object[array.length];
    String[] sArray = new String[array.length];

    for (int i = 0; i < array.length; i++) {
        sArray[i] = array[i].toString();
        if (sArray[i].contains("Database") || sArray[i].contains("Server") || sArray[i].contains("DATABASE")
                || sArray[i].contains("SERVER") || sArray[i].contains("DB")) {
            System.out.println("Object type");
            gArray[i] = graph.insertVertex(defaultParent, null, sArray[i], rech1, rech2, rech3, rech4,
                    "object");

        } else {
            System.out.println("Process type");
            gArray[i] = graph.insertVertex(defaultParent, null, sArray[i], rech1, rech2, rech3e, rech4,
                    "process");
        }
        rech1 += 100;
        rech2 += 100;
    }

    for (int i = 2; i <= rowct; i++) {

        if (a[i][3].equals("Two Way") || a[i][3].equals("TWO WAY") || a[i][3].equals("TwoWay")
                || a[i][3].equals("TWOWAY") || a[i][3].equals("2 Way") || a[i][3].equals("Two way")) {
            System.out.println("Double Edges");
            int l1 = 0, l2 = 0;
            for (int l = 1; l < gArray.length; l++) {
                System.out.println("gArray.toString=\t" + sArray[l]);
                System.out.println("gArray.length=\t" + sArray.length);
                if (sArray[l].equals(a[i][1])) {
                    l1 = l;
                    System.out.println("l2:\t" + l1);
                }
                if (sArray[l].equals(a[i][2])) {
                    l2 = l;
                    System.out.println("l2:\t" + l2);
                }
            }
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l1], gArray[l2], "agent");
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l2], gArray[l1], "agent");

        } else {
            System.out.println("Single Edges");
            int l1 = 0, l2 = 0;
            for (int l = 1; l < gArray.length; l++) {
                System.out.println("gArray.toString=\t" + sArray[l]);
                System.out.println("gArray.length=\t" + sArray.length);
                if (sArray[l].equals(a[i][1])) {
                    l1 = l;
                    System.out.println("l2:\t" + l2);
                }
                if (sArray[l].equals(a[i][2])) {
                    l2 = l;
                    System.out.println("l2:\t" + l2);
                }
            }
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l1], gArray[l2], "agent");
        }
    }

    graph.setEnabled(true);

    graph.setAutoSizeCells(true);

    graph.getModel().endUpdate();

    graphComponent = new mxGraphComponent(graph);
    mxFastOrganicLayout layout = new mxFastOrganicLayout(graph);
    // define layout

    //set all properties
    layout.setMinDistanceLimit(1);
    //layout.setInitialTemp(5);
    //layout.setInitialTemp(10);
    //layout.setForceConstant(10);
    //layout.setDisableEdgeStyle(true);
    //layout graph
    //layout.execute(graph.getDefaultParent());
    // layout using morphing
    String fileWPath;

    graph.getModel().beginUpdate();
    try {
        layout.execute(graph.getDefaultParent());
    } finally {
        mxMorphing morph = new mxMorphing(graphComponent, 20, 1.2, 20);

        morph.addListener(mxEvent.DONE, new mxIEventListener() {

            @Override
            public void invoke(Object arg0, mxEventObject arg1) {
                graph.getModel().endUpdate();
                // fitViewport();
            }

        });

        BufferedImage image;
        image = mxCellRenderer.createBufferedImage(graph, null, 2, Color.WHITE, true, null);
        Document d = mxCellRenderer.createVmlDocument(graph, null, 1, Color.WHITE, null);
        pathToWeb = getServletContext().getRealPath(File.separator);
        System.out.println("pathtoweb:\t" + pathToWeb);
        fileWPath = pathToWeb + "genImg\\" + userid + docid + ".png";
        System.out.println("filewpath:\t" + fileWPath);
        //System.out.println(pathToWeb + userid + docid + ".svg");
        ImageIO.write(image, "PNG", new File(fileWPath));
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
                new FileOutputStream(new File(pathToWeb + "genXML\\" + userid + docid + ".xml"))));
        encoder.writeObject(graph);
        encoder.close();
        morph.startAnimation();
    }

    graphComponent.setConnectable(false);
    fr.getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.WHITE));
    // Inhibit edge creation in the graph.
    fr.getContentPane().add(graphComponent);

    //fr.setVisible(true);

    request.setAttribute("docidM", docid);
    request.setAttribute("useridM", userid);
    request.setAttribute("colCountM", colct);
    request.setAttribute("rowCountM", rowct);
    request.setAttribute("fileLinkM", fileWPath);
    request.setAttribute("pathToWebM", pathToWeb);
    System.out.println("Iteration Complete");

    getServletContext().getRequestDispatcher("/success.jsp").forward(request, response);

}

From source file:com.anevis.jfreechartsamplespring.reader.FileReaderServiceImpl.java

@Override
public List<PieChartData> readPieChartDataFromXls(String filepath) {
    InputStream stream;/*w  w  w. j  a v a2  s. c o m*/

    try {
        stream = new FileInputStream(filepath);
        List<PieChartData> pieChartDataList = new ArrayList<>();
        HSSFWorkbook workbook = new HSSFWorkbook(stream);

        HSSFSheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.iterator();
        rowIterator.next();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            PieChartData data = new PieChartData();

            Cell countryCell = row.getCell(0);
            Cell weightCell = row.getCell(1);

            if (countryCell != null && weightCell != null) {
                data.setCountry(countryCell.getStringCellValue());
                data.setWeight(weightCell.getNumericCellValue());

                pieChartDataList.add(data);
            }
        }

        return pieChartDataList;

    } catch (IOException ex) {
        Logger.getLogger(FileReaderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:com.anphat.customer.controller.CommonUploader.java

public void createFileError(String err, List<Integer> lstRows) {
    if (DataUtil.isListNullOrEmpty(lstRows)) {
        return;/*from ww w  .jav  a2s  . c  o m*/
    }
    cellStyle = null;
    if (isCreateSheet) {
        try {
            // sheet
            fileInput = new FileInputStream(tempFile);
            fileOut = new FileOutputStream(fileErrorName);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        // sheet loi
        workbookEp = new XSSFWorkbook();
        worksheetEp = workbookEp.createSheet("error");
        cellStyle = null;
        hSSFWorkbook = null;
        worksheetIp = null;
        row5 = null;
        cellB1 = null;
        isCreateSheet = false;
        //
        workbookIp = null;
        if (mimeType.equalsIgnoreCase(Constants.FORMATFILE.EXCEL_XLSX)) {
            try {
                // xlsx
                workbookIp = new XSSFWorkbook(fileInput);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else if (mimeType.equalsIgnoreCase(Constants.FORMATFILE.EXCEL_XLS)) { // xls
            HSSFWorkbook hSSFWorkbook = null;
            try {
                hSSFWorkbook = new HSSFWorkbook(fileInput);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            workbookIp = ExcelReaderXLSX.convertWorkbookHSSFToXSSF(hSSFWorkbook);
        }
        XSSFSheet worksheetNew = workbookIp.getSheetAt(0);
        ExcelReaderXLSX.copySheets(worksheetEp, worksheetNew, 8);
        // style
        cellStyle = CommonUtils.styleCell(workbookEp);
    }
    for (Integer row : lstRows) {
        row5 = worksheetEp.getRow(row + 1);
        if (row5 != null) {
            isError = true;
            cellB1 = row5.createCell(9);
            cellB1.setCellValue(err);
            cellB1.setCellStyle(cellStyle);
        }
    }
}

From source file:com.anphat.customer.controller.CommonUploader.java

public void createFileError(String err, int i) {
    cellStyle = null;//  ww w.  j a va2  s. c o m
    if (isCreateSheet) {
        try {
            // sheet
            flieInput = new FileInputStream(tempFile);
            fileOut = new FileOutputStream(fileErrorName);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        workbookIp = null;
        // sheet loi
        workbookEp = new XSSFWorkbook();
        worksheetEp = workbookEp.createSheet("error");
        cellStyle = null;

        hSSFWorkbook = null;
        worksheetIp = null;
        row5 = null;
        cellB1 = null;
        isCreateSheet = false;
        //
        workbookIp = null;
        if (mimeType.equalsIgnoreCase(Constants.FORMATFILE.EXCEL_XLSX)) {
            try {
                // xlsx
                workbookIp = new XSSFWorkbook(flieInput);
            } catch (IOException ex) {
            }
        } else if (mimeType.equalsIgnoreCase(Constants.FORMATFILE.EXCEL_XLS)) { // xls
            HSSFWorkbook hSSFWorkbook = null;
            try {
                hSSFWorkbook = new HSSFWorkbook(flieInput);
            } catch (IOException ex) {
            }
            workbookIp = ExcelReaderXLSX.convertWorkbookHSSFToXSSF(hSSFWorkbook);
        }
        XSSFSheet worksheetIp = workbookIp.getSheetAt(0);
        ExcelReaderXLSX.copySheets(worksheetEp, worksheetIp, 8);
        // style
        cellStyle = CommonUtils.styleCell(workbookEp);
    }
    row5 = worksheetEp.getRow(i + 1);
    if (row5 != null) {
        cellB1 = row5.createCell(9);
        cellB1.setCellValue(err);
        cellB1.setCellStyle(cellStyle);
    }
}