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

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

Introduction

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

Prototype

@Override
public XSSFRichTextString getRichStringCellValue() 

Source Link

Document

Get the value of the cell as a XSSFRichTextString

For numeric cells we throw an exception.

Usage

From source file:com.appdynamics.jrbronet.projectplan.ExcelManager.java

private static void copyRow(XSSFWorkbook workbook, XSSFSheet sourceWorksheet, int sourceRowNum,
        XSSFSheet destinationWorksheet, int destinationRowNum) {
    // Get the source / new row
    XSSFRow newRow = destinationWorksheet.getRow(destinationRowNum);
    XSSFRow sourceRow = sourceWorksheet.getRow(sourceRowNum);

    // If the row exist in destination, push down all rows by 1 else create a new row

    if (newRow != null) {
        destinationWorksheet.shiftRows(destinationRowNum, destinationWorksheet.getLastRowNum(), 1);
    } else {//w ww.j  a  v  a2 s  . com
        newRow = destinationWorksheet.createRow(destinationRowNum);
    }

    // Loop through source columns to add to new row
    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        // Grab a copy of the old/new cell
        XSSFCell oldCell = sourceRow.getCell(i);
        XSSFCell newCell = newRow.createCell(i);

        // If the old cell is null jump to next cell
        if (oldCell == null) {
            newCell = null;
            continue;
        }

        // Copy style from old cell and apply to new cell
        XSSFCellStyle newCellStyle = workbook.createCellStyle();
        newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
        ;
        newCell.setCellStyle(newCellStyle);

        // If there is a cell comment, copy
        if (oldCell.getCellComment() != null) {
            newCell.setCellComment(oldCell.getCellComment());
        }

        // If there is a cell hyperlink, copy
        if (oldCell.getHyperlink() != null) {
            newCell.setHyperlink(oldCell.getHyperlink());
        }

        // Set the cell data type
        newCell.setCellType(oldCell.getCellType());

        //newCell.setCellValue(oldCell.getRawValue());
        //newCell.setCellType(oldCell.getCellType());                        

        // Set the cell data value
        switch (oldCell.getCellType()) {
        case Cell.CELL_TYPE_BLANK:
            newCell.setCellValue(oldCell.getStringCellValue());
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            newCell.setCellValue(oldCell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_ERROR:
            newCell.setCellErrorValue(oldCell.getErrorCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA:
            newCell.setCellFormula(oldCell.getCellFormula());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            newCell.setCellValue(oldCell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:
            newCell.setCellValue(oldCell.getRichStringCellValue());
            break;
        }

    }

    // If there are are any merged regions in the source row, copy to new row
    /*
    for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
    CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
    if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
        CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
                (newRow.getRowNum() +
                        (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow()
                                )),
                cellRangeAddress.getFirstColumn(),
                cellRangeAddress.getLastColumn());
        worksheet.addMergedRegion(newCellRangeAddress);
    }            
    }
    */
}

From source file:com.esd.cs.common.XExcelSheetParser.java

License:Open Source License

private Object getCellString(XSSFCell cell) {
    // TODO Auto-generated method stub
    Object result = null;/*  ww  w  .  ja v  a 2 s .  co m*/
    if (cell != null) {
        // ?Numeric:0,String:1,Formula:2,Blank:3,Boolean:4,Error:5
        int cellType = cell.getCellType();
        switch (cellType) {
        case HSSFCell.CELL_TYPE_STRING:
            result = cell.getRichStringCellValue().getString();
            break;
        case HSSFCell.CELL_TYPE_NUMERIC:
            result = cell.getNumericCellValue();
            break;
        case HSSFCell.CELL_TYPE_FORMULA:
            result = cell.getNumericCellValue();
            break;
        case HSSFCell.CELL_TYPE_BOOLEAN:
            result = cell.getBooleanCellValue();
            break;
        case HSSFCell.CELL_TYPE_BLANK:
            result = null;
            break;
        case HSSFCell.CELL_TYPE_ERROR:
            result = null;
            break;
        default:
            break;
        }
    }
    return result;
}

From source file:com.krawler.spring.importFunctionality.ImportUtil.java

License:Open Source License

/**
 * Generate the preview of the xls grid//w  w w. j  a va  2  s .  c o  m
 * @param filename
 * @param sheetNo
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject parseXLSX(String filename, int sheetNo)
        throws FileNotFoundException, IOException, JSONException {
    JSONObject jobj = new JSONObject();
    FileInputStream fs = new FileInputStream(filename);
    XSSFWorkbook wb = new XSSFWorkbook(fs);
    XSSFSheet sheet = wb.getSheetAt(sheetNo);
    //DateFormat sdf = new SimpleDateFormat(df);

    int startRow = 0;
    int maxRow = sheet.getLastRowNum();
    int maxCol = 0;
    int noOfRowsDisplayforSample = 20;
    if (noOfRowsDisplayforSample > sheet.getLastRowNum()) {
        noOfRowsDisplayforSample = sheet.getLastRowNum();
    }

    JSONArray jArr = new JSONArray();
    try {
        for (int i = 0; i <= noOfRowsDisplayforSample; i++) {
            XSSFRow row = sheet.getRow(i);
            JSONObject obj = new JSONObject();
            JSONObject jtemp1 = new JSONObject();
            if (row == null) {
                continue;
            }
            if (i == 0) {
                maxCol = row.getLastCellNum();
            }
            for (int cellcount = 0; cellcount < maxCol; cellcount++) {
                XSSFCell cell = row.getCell(cellcount);
                CellReference cref = new CellReference(i, cellcount);
                String colHeader = cref.getCellRefParts()[2];
                String val = null;

                if (cell != null) {
                    switch (cell.getCellType()) {
                    case XSSFCell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            val = Long.toString(cell.getDateCellValue().getTime());
                        } else {
                            val = dfmt.format(cell.getNumericCellValue());
                        }
                        break;
                    case XSSFCell.CELL_TYPE_STRING:
                        val = ImportUtil.cleanHTML(cell.getRichStringCellValue().getString());
                        break;
                    }
                }

                if (i == 0) { // List of Headers (Consider first row as Headers)
                    if (val != null) {
                        jtemp1 = new JSONObject();
                        jtemp1.put("header", val == null ? "" : val);
                        jtemp1.put("index", cellcount);
                        jobj.append("Header", jtemp1);
                    }
                }
                obj.put(colHeader, val);
            }
            //                    if(obj.length()>0){ //Don't show blank row in preview grid[SK]
            jArr.put(obj);
            //                    }
        }
    } catch (Exception ex) {
        Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    jobj.put("startrow", startRow);
    jobj.put("maxrow", maxRow);
    jobj.put("maxcol", maxCol);
    jobj.put("index", sheetNo);
    jobj.put("data", jArr);
    jobj.put("filename", filename);

    jobj.put("msg", "XLSX has been successfully uploaded");
    jobj.put("lsuccess", true);
    jobj.put("valid", true);
    return jobj;
}

From source file:com.krawler.spring.importFunctionality.ImportUtil.java

License:Open Source License

/**
 * @param filename//www. j  av  a  2 s .  c  o m
 * @param sheetNo
 * @param startindex
 * @param importDao
 * @return
 * @throws ServiceException
 */
public static void dumpXLSXFileData(String filename, int sheetNo, int startindex, ImportDAO importDao,
        HibernateTransactionManager txnManager) throws ServiceException {
    boolean commitedEx = false;
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("import_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txnManager.getTransaction(def);
    Session session = txnManager.getSessionFactory().getCurrentSession();
    try {
        String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "xlsfiles";
        FileInputStream fs = new FileInputStream(destinationDirectory + "/" + filename);
        XSSFWorkbook wb = new XSSFWorkbook(fs);
        XSSFSheet sheet = wb.getSheetAt(sheetNo);
        //DateFormat sdf = new SimpleDateFormat(df_full);
        int maxRow = sheet.getLastRowNum();
        int maxCol = 0;
        String tableName = importDao.getTableName(filename);
        int flushCounter = 0;
        for (int i = startindex; i <= maxRow; i++) {
            XSSFRow row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            if (i == startindex) {
                maxCol = row.getLastCellNum(); //Column Count
            }
            ArrayList<String> dataArray = new ArrayList<String>();
            JSONObject dataObj = new JSONObject();
            for (int j = 0; j < maxCol; j++) {
                XSSFCell cell = row.getCell(j);
                String val = null;
                if (cell == null) {
                    dataArray.add(val);
                    continue;
                }
                String colHeader = new CellReference(i, j).getCellRefParts()[2];
                switch (cell.getCellType()) {
                case XSSFCell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        val = Long.toString(cell.getDateCellValue().getTime());
                    } else {
                        val = dfmt.format(cell.getNumericCellValue());
                    }
                    break;
                case XSSFCell.CELL_TYPE_STRING:
                    val = ImportUtil.cleanHTML(cell.getRichStringCellValue().getString());
                    break;
                }
                dataObj.put(colHeader, val);
                dataArray.add(val); //Collect row data
            }
            //Insert Query
            if (dataObj.length() > 0) { // Empty row check (if lenght==0 then all columns are empty)
                importDao.dumpFileRow(tableName, dataArray.toArray());
                if (flushCounter % 30 == 0) {
                    session.flush();
                    session.clear();
                }
                flushCounter++;
            }

        }
        try {
            txnManager.commit(status);
        } catch (Exception ex) {
            commitedEx = true;
            throw ex;
        }
    } catch (IOException ex) {
        throw ServiceException.FAILURE("dumpXLSXFileData: " + ex.getMessage(), ex);
    } catch (Exception ex) {
        if (!commitedEx) { //if exception occurs during commit then dont call rollback
            txnManager.rollback(status);
        }
        throw ServiceException.FAILURE("dumpXLSXFileData: " + ex.getMessage(), ex);
    }
}

From source file:com.uiconf.MainWindow.java

private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
    JFileChooser c = new JFileChooser();
    FileFilter xlsFilter = new FileTypeFilter(".xlsx", "Microsoft Excel Documents");
    c.addChoosableFileFilter(xlsFilter);
    c.showOpenDialog(MainWindow.this);
    File file = c.getSelectedFile();

    //Load and parse from xls uiConf list configuration
    uiConfVectorHolder.clear();/*from w  ww  .  jav a 2 s  . c  om*/
    uiConfVectorHolder = XmlUtils.importExcelSheet(file);
    lblLoadFile.setText(c.getCurrentDirectory().toString() + "\\" + c.getSelectedFile().getName());
    lblLoadFile.repaint();

    //Create List of UiConfEntry (From xls file)
    Vector<?> vcell;
    XSSFCell cell;
    String extension;
    String uiConfId;
    String description;
    String uiConfType;

    Iterator<?> it = uiConfVectorHolder.iterator();
    while (it.hasNext()) {
        vcell = (Vector<?>) it.next();
        cell = (XSSFCell) vcell.get(0); //extension
        cell.setCellType(Cell.CELL_TYPE_STRING);
        extension = cell.getRichStringCellValue().getString();

        //Discard first entry
        if (extension.equals("extension")) {
            continue;
        }
        uiConfCounter++;

        cell = (XSSFCell) vcell.get(1); //uiConfId
        cell.setCellType(Cell.CELL_TYPE_STRING);
        uiConfId = cell.getRichStringCellValue().getString();

        cell = (XSSFCell) vcell.get(2); //description
        cell.setCellType(Cell.CELL_TYPE_STRING);
        description = cell.getRichStringCellValue().getString();

        cell = (XSSFCell) vcell.get(3); //type
        cell.setCellType(Cell.CELL_TYPE_STRING);
        uiConfType = cell.getRichStringCellValue().getString();

        UiConfContainer.uiConfList.add(new UiConfEntry(uiConfCounter, extension, Integer.valueOf(uiConfId),
                description, UiConfTypeEnum.getUiConfTypeEnumFromString(uiConfType)));
    }
    if (!UiConfContainer.uiConfList.isEmpty()) {
        fileIsLoaded = true;
    }

    if (fileIsLoaded && isConnected) {
        btnStart.setEnabled(true);
        jmnOpenHtmlPlayer.setEnabled(true);
        jmnOpenAllKCW.setEnabled(true);
        jmnOpenAllPlayers.setEnabled(true);
    }

    //Run in new thread  - Create HTML test pages
    Thread thread = new Thread() {
        @Override
        public void run() {
            logger.info("Creating HTML test pages...");
            uiConfContainer.preparePlayerHTMLfiles();
            logger.info("DONE creating HTML test pages\n");
        }

    };
    thread.start();

}

From source file:com.viettel.hqmc.DAO.FilesDAO.java

/**
 * import du lieu tu excel//from  w  w  w . ja  v  a2s . co  m
 *
 * @return
 */
public String importFileFromExcel() throws FileNotFoundException, IOException, ParseException {
    List fileInfo = new ArrayList();
    String strReturn = ERROR_PERMISSION;
    //        TechnicalStandard ts = new TechnicalStandard();
    TechnicalStandardDAOHE tshe = new TechnicalStandardDAOHE();
    String err = "";
    Long attachId = Long.parseLong(getRequest().getParameter("attachId"));//get attactId
    VoAttachs att = (VoAttachs) getSession().get("com.viettel.voffice.database.BO.VoAttachs", attachId);//Attachs BO
    if (att == null) {
        fileInfo.add("File not found");
        err += "File not found";
    } else {
        Category item;
        ResourceBundle rb = ResourceBundle.getBundle("config");//get link tuong doi
        String dir = rb.getString("directoryExcel");
        String linkFile = att.getAttachPath();
        linkFile = dir + linkFile;
        createForm.setPath(linkFile);
        InputStream myxls = new FileInputStream(linkFile);//get file excel
        XSSFWorkbook wb = new XSSFWorkbook(myxls);

        XSSFRow row = null;
        String matchingTarget = null;
        XSSFCell productName = null;
        XSSFCell businessTaxCode = null;
        XSSFCell manufactorAddress = null;
        XSSFCell manufactorName = null;
        XSSFCell manufactorTel = null;
        XSSFCell manufactorFax = null;
        XSSFCell manufactorEmail = null;
        XSSFCell nationName = null;
        XSSFCell signer = null;
        XSSFCell assessmentMethod = null;
        XSSFCell annoucementNo = null;

        XSSFCell pushlishDate = null;
        XSSFCell nationCompanyName = null;
        XSSFCell nationCompanyAddress = null;
        try {

            XSSFSheet sheet = wb.getSheetAt(0);
            try {
                //                    XSSFSheet sheet1 = wb.getSheetAt(1);
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                //                    log.error(e.getMessage());
                err += "Khng tm thy Sheet Chi tit sn phm, ";
            }

            try {
                //                    XSSFSheet sheet2 = wb.getSheetAt(2);
            } catch (Exception ex) {
                //                    log.error(e.getMessage());
                LogUtil.addLog(ex);//binhnt sonar a160901
                err += "Khng tm thy Sheet Ch tiu cht lng ch yu, ";
            }

            try {
                //                    XSSFSheet sheet3 = wb.getSheetAt(3);
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                //                    log.error(e.getMessage());
                err += "Khng tm thy Sheet Ch tiu vi sinh vt, ";
            }

            try {
                //                    XSSFSheet sheet4 = wb.getSheetAt(4);
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                //                    log.error(e.getMessage());
                err += "Khng tm thy Sheet Hm lng kim loi nng, ";
            }
            try {
                //                    XSSFSheet sheet5 = wb.getSheetAt(5);
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                //                    log.error(e.getMessage());
                err += "Khng tm thy Sheet Hm lng ha cht, ";
            }
            try {
                //                    XSSFSheet sheet6 = wb.getSheetAt(6);
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                //                    log.error(e.getMessage());
                err += "Khng tm thy Sheet K hoch kim sot cht lng, ";
            }

            if (sheet == null) {
                err += "Khng tm thy Sheet Bn cng b, ";
            } else {
                String sheetName = sheet.getSheetName();
                if (!"Ban_Cong_bo".equals(sheetName)) {
                    err += "Sai tn sheet Bn cng b, ";
                }
            }

            //                XSSFRow firstRow = sheet.getRow(1);
            int rowNums = sheet.getLastRowNum();
            //                UsersDAOHE sdhe = new UsersDAOHE();
            //                SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            row = sheet.getRow(1);
            businessTaxCode = row.getCell((short) 1);
            productName = row.getCell((short) 3);
            row = sheet.getRow(4);
            manufactorName = row.getCell((short) 1);
            manufactorAddress = row.getCell((short) 3);
            row = sheet.getRow(5);
            manufactorTel = row.getCell((short) 1);
            manufactorFax = row.getCell((short) 3);
            row = sheet.getRow(6);
            manufactorEmail = row.getCell((short) 1);
            nationName = row.getCell((short) 3);
            row = sheet.getRow(7);
            nationCompanyName = row.getCell((short) 1);
            nationCompanyAddress = row.getCell((short) 3);

            row = sheet.getRow(10);
            annoucementNo = row.getCell((short) 1);
            pushlishDate = row.getCell((short) 3);
            row = sheet.getRow(11);
            signer = row.getCell((short) 1);
            assessmentMethod = row.getCell((short) 3);
            matchingTarget = "";
            String standardCode;
            for (int i = 12; i < rowNums; i++) {
                row = sheet.getRow(i);
                if (row.getCell((short) 1).toString() != "") {
                    XSSFCell standardCodeCell = row.getCell((short) 1);
                    standardCode = standardCodeCell.getRichStringCellValue().toString();
                    if (tshe.findStandardByCode(standardCode)) {
                        XSSFCell matchingTargetCell = row.getCell((short) 2);
                        matchingTarget += matchingTargetCell.getRichStringCellValue() + ";";
                    } else {
                        err += "Quy chun (quy nh) " + standardCode + " khng chnh xc ! ";
                        break;
                    }
                } else {
                    break;
                }
            }

        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            //                log.error(e.getMessage());
            err += "li tab bn cng b hp quy ";
        }
        if (matchingTarget != "" && matchingTarget != null) {
            matchingTarget = matchingTarget.substring(0, matchingTarget.length() - 1);
        }
        //tab chi tiet san pham
        XSSFCell productNo = null;
        XSSFCell productStatus = null;
        XSSFCell productColor = null;
        XSSFCell productSmell = null;
        XSSFCell productOtherstatus = null;
        XSSFCell productType = null;
        XSSFCell otherTarget = null;
        XSSFCell component = null;
        XSSFCell timeinuse = null;
        XSSFCell useage = null;
        XSSFCell objectInUse = null;
        XSSFCell guideline = null;
        //XSSFCell packageRecipe = null;
        XSSFCell packageMaterial = null;
        XSSFCell productProcess = null;
        XSSFCell counterfeitDistinctive = null;
        XSSFCell origin = null;
        XSSFCell signDate = null;
        XSSFCell signer_productdetails = null;
        XSSFCell chemicalTargetUnwanted = null;
        try {

            XSSFSheet sheet1 = wb.getSheetAt(1);
            if (sheet1 == null) {
                err += "Khng tm thy Sheet Chi tit sn phm, ";

            } else {
                String sheetName = sheet1.getSheetName();
                if (!"Chi_tiet_san_pham".equals(sheetName)) {
                    err += "Sai tn Sheet Chi tit sn phm, ";
                }
            }

            row = sheet1.getRow(1);
            productType = row.getCell((short) 1);
            productNo = row.getCell((short) 3);
            row = sheet1.getRow(4);
            productStatus = row.getCell((short) 1);
            productColor = row.getCell((short) 3);
            row = sheet1.getRow(5);
            productSmell = row.getCell((short) 1);
            productOtherstatus = row.getCell((short) 3);
            row = sheet1.getRow(13);
            otherTarget = row.getCell((short) 1);
            row = sheet1.getRow(14);
            component = row.getCell((short) 1);
            timeinuse = row.getCell((short) 3);
            row = sheet1.getRow(15);
            useage = row.getCell((short) 1);
            objectInUse = row.getCell((short) 3);
            row = sheet1.getRow(16);
            guideline = row.getCell((short) 1);
            packageMaterial = row.getCell((short) 3);
            row = sheet1.getRow(17);
            productProcess = row.getCell((short) 3);
            //packageRecipe = row.getCell((short) 1);
            row = sheet1.getRow(18);
            counterfeitDistinctive = row.getCell((short) 1);
            origin = row.getCell((short) 3);
            row = sheet1.getRow(19);
            signDate = row.getCell((short) 1);
            signer_productdetails = row.getCell((short) 3);
            // bo sung ham luong hoa chat khong mong muon
            XSSFSheet sheet5 = wb.getSheetAt(5);

            int rowNums = sheet5.getLastRowNum();
            do {
                row = sheet5.getRow(rowNums);
                chemicalTargetUnwanted = row.getCell((short) 2);
                rowNums--;
            } while (chemicalTargetUnwanted == null);

            //                chemicalTargetUnwanted = row.getCell((short) 2);
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            //                log.error(e.getMessage());
            err += "Li tab chi tit sn phm ";
        }
        // do du lieu vao form
        Long fileId = getRequest().getParameter("fileId") == null ? 0L
                : Long.parseLong(getRequest().getParameter("fileId"));
        Long fileType = getRequest().getParameter("fileType") == null ? 0L
                : Long.parseLong(getRequest().getParameter("fileType"));
        if (fileType > 0L && fileId > 0L) {
            createForm = new FilesForm();
            createForm.setFileType(fileType);
            createForm.setFileId(fileId);
        }
        UsersDAOHE udhe = new UsersDAOHE();
        Users user = udhe.findById(getUserId());

        BusinessDAOHE bdhe = new BusinessDAOHE();
        Business bus = bdhe.findById(user.getBusinessId());

        if (createForm.getFileId() != null && createForm.getFileId() > 0l) {
            FilesDAOHE fdhe = new FilesDAOHE();
            createForm = fdhe.getFilesDetail(createForm.getFileId());
            if (!createForm.getFileType().equals(0L)) {
                ProcedureDAOHE cdhe = new ProcedureDAOHE();
                List lstTTHC = cdhe.getProcedureForChange(createForm.getFileType());
                lstCategory = new ArrayList();
                lstCategory.addAll(lstTTHC);
                lstCategory.add(0,
                        new Procedure(Constants.COMBOBOX_HEADER_VALUE, Constants.COMBOBOX_HEADER_TEXT_SELECT));
                getRequest().setAttribute("lstFileType", lstCategory);

            }
        }

        if (createForm.getFileType() != null && createForm.getFileType() > 0l) {
            ProcedureDAOHE pdhe = new ProcedureDAOHE();
            CategoryDAOHE cdhe = new CategoryDAOHE();
            TechnicalStandardDAOHE tdhe = new TechnicalStandardDAOHE();
            FilesDAOHE fdhe = new FilesDAOHE();
            if (!fileType.equals(0L)) {
                createForm.setFileType(fileType);
            }
            Procedure tthc = pdhe.findById(createForm.getFileType());
            if (tthc != null) {

                lstProductType = cdhe.findAllCategory("SP");
                lstUnit = cdhe.findAllCategory("DVI");

                lstStandard = tdhe.findAllStandard();
                String lstDepts = convertToJSONData(lstStandard, "vietnameseName", "vietnameseName");
                getRequest().setAttribute("lstStandard", lstDepts);

                UserAttachsDAOHE uahe = new UserAttachsDAOHE();
                lstUserAttach = uahe.findAllUserAttach(getUserId());
                String lstUserAttachs = convertToJSONData(lstUserAttach, "attachName", "attachName");
                getRequest().setAttribute("lstUserAttach", lstUserAttachs);
                if (lstUserAttachs.trim().length() > 0) {
                    createForm.setCountUA(1L);
                } else {
                    createForm.setCountUA(0L);
                }
                getRequest().setAttribute("lstProductType", lstProductType);
                getRequest().setAttribute("lstUnit", lstUnit);

                String fileLst = tthc.getFileList();
                getRequest().setAttribute("fileList", com.viettel.common.util.StringUtils.removeHTML(fileLst));
                getRequest().setAttribute("agencyName", getDepartmentName());
                getRequest().setAttribute("fileNameFull", tthc.getName());
                strReturn = tthc.getDescription();
                if (createForm.getAnnouncement() != null) {
                    if (createForm.getAnnouncement().getAnnouncementNo() != null
                            && createForm.getAnnouncement().getAnnouncementNo().length() > 0l) {
                        return strReturn;
                    }
                }
                if (strReturn.equals(Constants.FILE_DESCRIPTION.ANNOUNCEMENT_FILE01)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.ANNOUNCEMENT_FILE03)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.CONFIRM_FUNC_IMP)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.CONFIRM_FUNC_VN)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.CONFIRM_NORMAL_IMP)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.CONFIRM_NORMAL_VN)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.REC_CONFIRM_NORMAL_IMP)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.RE_ANNOUNCEMENT)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.RE_CONFIRM_FUNC_IMP)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.RE_CONFIRM_FUNC_VN)
                        || strReturn.equals(Constants.FILE_DESCRIPTION.RE_CONFIRM_NORMAL_VN)) {
                    String announcementNoStr = fdhe.getReceiptNoNew(getUserId(), getUserLogin(),
                            createForm.getFileType());
                    createForm.setAnnouncement(new AnnouncementForm());
                    createForm.getAnnouncement().setAnnouncementNo(announcementNoStr);
                    // thong tin doanh nghiep
                    createForm.getAnnouncement().setBusinessAddress(bus.getBusinessAddress());
                    createForm.getAnnouncement().setBusinessFax(bus.getBusinessFax());
                    createForm.getAnnouncement().setBusinessName(bus.getBusinessName());
                    createForm.getAnnouncement().setBusinessTelephone(bus.getBusinessTelephone());
                    createForm.getAnnouncement().setBusinessEmail(bus.getUserEmail());
                    createForm.getAnnouncement().setBusinessLicence(bus.getBusinessLicense());

                    // ho so cap lai 7-11
                    createForm.setReIssueForm(new ReIssueFormForm());
                    createForm.getReIssueForm().setBusinessName(bus.getBusinessName());
                    createForm.getReIssueForm().setIdentificationNumber(bus.getBusinessLicense());
                    createForm.getReIssueForm().setAddress(bus.getBusinessAddress());
                    createForm.getReIssueForm().setEmail(bus.getUserEmail());
                    createForm.getReIssueForm().setTelephone(bus.getBusinessTelephone());
                    createForm.getReIssueForm().setFax(bus.getBusinessFax());
                    //set thong tin tu excel

                    try {
                        if (businessTaxCode != null && user.getUserName().equals(businessTaxCode.toString())) {
                            if (matchingTarget != "" && matchingTarget != null) {
                                createForm.getAnnouncement().setMatchingTarget(matchingTarget.toString());
                            }
                            createForm.getAnnouncement().setProductName(productName.toString());
                            createForm.getAnnouncement().setManufactureAddress(manufactorAddress.toString());
                            createForm.getAnnouncement().setManufactureName(manufactorName.toString());
                            createForm.getAnnouncement().setManufactureTel(manufactorTel.toString());
                            createForm.getAnnouncement().setManufactureFax(manufactorFax.toString());
                            createForm.getAnnouncement().setManufactureEmail(manufactorEmail.toString());
                            createForm.getAnnouncement().setNationName(nationName.toString());
                            createForm.getAnnouncement().setSigner(signer.toString());
                            createForm.getAnnouncement()
                                    .setNationCompanyAddress(nationCompanyAddress.toString());
                            createForm.getAnnouncement().setNationCompanyName(nationCompanyName.toString());
                            createForm.getAnnouncement().setAssessmentMethod(assessmentMethod.toString());
                            if (pushlishDate.toString() != null && pushlishDate.toString().length() > 0) {
                                createForm.getAnnouncement().setPublishDate(DateTimeUtils
                                        .convertStringToTime(pushlishDate.toString(), "dd/MM/yyyy"));
                            }
                            createForm.getAnnouncement().setAnnouncementNo(annoucementNo.toString());
                            //tab thong tin chi tiet
                            createForm.setDetailProduct(new DetailProductForm());
                            createForm.getDetailProduct().setProductNo(productNo.toString());
                            createForm.getDetailProduct().setProductStatus(productStatus.toString());
                            createForm.getDetailProduct().setProductColor(productColor.toString());
                            createForm.getDetailProduct().setProductSmell(productSmell.toString());
                            createForm.getDetailProduct().setProductOtherStatus(productOtherstatus.toString());

                            item = cdhe.findCategoryByName("SP", productType.toString());
                            if (item != null) {
                                createForm.getDetailProduct().setProductType(item.getCategoryId());
                            } else {
                                err += "Danh mc " + productType.toString() + " khng chnh xc, ";
                            }

                            createForm.getDetailProduct().setOtherTarget(otherTarget.toString());
                            createForm.getDetailProduct().setComponents(component.toString());
                            createForm.getDetailProduct().setTimeInUse(timeinuse.toString());
                            createForm.getDetailProduct().setUseage(useage.toString());
                            createForm.getDetailProduct().setObjectUse(objectInUse.toString());
                            createForm.getDetailProduct().setGuideline(guideline.toString());
                            //createForm.getDetailProduct().setPackageRecipe(packageRecipe.toString());
                            createForm.getDetailProduct().setPackateMaterial(packageMaterial.toString());
                            createForm.getDetailProduct().setProductionProcess(productProcess.toString());
                            createForm.getDetailProduct()
                                    .setCounterfeitDistinctive(counterfeitDistinctive.toString());
                            createForm.getDetailProduct().setOrigin(origin.toString());
                            if (signDate.toString() != null && signDate.toString().length() > 0) {
                                createForm.getDetailProduct().setSignDate(
                                        DateTimeUtils.convertStringToTime(signDate.toString(), "dd/MM/yyyy"));
                            }
                            createForm.getDetailProduct().setSigner(signer_productdetails.toString());
                            createForm.getDetailProduct()
                                    .setChemicalTargetUnwanted(chemicalTargetUnwanted.toString());
                            createForm.setStatusExcel(
                                    err += "Thm mi bn cng b hp quy thnh cng ");
                        } else {
                            createForm.setStatusExcel(err += "M s thu khng chnh xc ");
                        }
                    } catch (Exception ex) {
                        //                            log.error(parseException);
                        LogUtil.addLog(ex);//binhnt sonar a160901
                        createForm.setStatusExcel(
                                err += "Thm mi bn cng b hp quy khng thnh cng ");
                    }
                }
            }
        }
    }
    CategoryDAOHE ctdhe = new CategoryDAOHE();
    Category cate = ctdhe.findCategoryByTypeAndCode("SP", "TPCN");
    Category cateTL = ctdhe.findCategoryByTypeAndCode("SP", "TL");
    List<Category> cate1 = ctdhe.findCategoryByTypeAndCodeNew("SP", "DBT");
    String dbtId = "";
    for (int i = 0; i < cate1.size(); i++) {
        dbtId += cate1.get(i).getCategoryId().toString() + ";";
    }
    Long tpcnId = cate.getCategoryId();
    Long tlId = cateTL.getCategoryId();
    FeeDAOHE fdhe1 = new FeeDAOHE();
    Fee findfee1 = fdhe1.findFeeByCode("TPDB");
    Long priceTPDB = findfee1.getPrice();
    Fee findfee2 = fdhe1.findFeeByCode("TPCN");
    Long priceTPCN = findfee2.getPrice();
    Fee findfee3 = fdhe1.findFeeByCode("TPK");
    Long priceETC = findfee3.getPrice();
    getRequest().setAttribute("dbtId", dbtId);
    getRequest().setAttribute("tpcnId", tpcnId);
    getRequest().setAttribute("tlId", tlId);
    getRequest().setAttribute("priceTPCN", priceTPCN);
    getRequest().setAttribute("priceTPDB", priceTPDB);
    getRequest().setAttribute("priceETC", priceETC);

    return strReturn;
}

From source file:localization.excel.java

public static void convert(String filePath) {
    Vector<String> zFile;
    if (filePath.endsWith(".zip")) {
        zFile = readzipfile(filePath);//from  w w w  .j  a  va2  s. c  o  m
        for (String s : zFile) {
            if (s.endsWith(".xlsx")) {
                //System.out.println(s);
                convert(s);
            }
        }
    } else if (!filePath.endsWith(".xlsx")) {
        return;
    } else {
        try {
            FileInputStream file = new FileInputStream(new File(filePath));
            System.out.println(filePath);
            //Get the workbook instance for XLS file 
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFRow row;
            XSSFCell cell;
            rowNumber = sheet.getPhysicalNumberOfRows();
            try {
                for (int i = 0; i < rowNumber; i++) {
                    row = sheet.getRow(i);
                    if (row != null) {
                        int columnNum = row.getPhysicalNumberOfCells();
                        //System.out.println(columnNum);
                        for (int j = 0; j < columnNum; j++) {
                            cell = row.getCell(j);

                            if (j == 0) {
                                String name = cell.getRichStringCellValue().getString();
                                if (name.equalsIgnoreCase("Esri")) {
                                    langNumber++;
                                }
                                //System.out.println(name);
                            }
                        }
                        if (i == 3) {
                            cell = row.getCell(30);
                            XSSFCellStyle cs = cell.getCellStyle();
                            cell = row.createCell(32);
                            cell.setCellValue("Additional Charge per language");
                            cell.setCellStyle(cs);
                        }
                    }
                }
            } catch (Exception e) {

            }
            System.out.println(langNumber);
            double total = Double.parseDouble(sheet.getRow(langNumber + 3).getCell(29).getRawValue());

            double subTotal = total / langNumber;
            DecimalFormat df = new DecimalFormat("#.000");
            for (int i = 0; i < langNumber; i++) {
                cell = sheet.getRow(i + 4).createCell(32);
                cell.setCellValue("$" + df.format(subTotal));
            }

            file.close();
            FileOutputStream outFile = new FileOutputStream(filePath);
            workbook.write(outFile);
            outFile.close();
            rowNumber = 0;
            langNumber = 0;
            System.out.println("Done");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:net.mcnewfamily.rmcnew.shared.Util.java

License:Open Source License

public static void copyXSSFCell(XSSFCell srcCell, XSSFCell destCell) {
    if (srcCell != null && destCell != null) {
        switch (srcCell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
            destCell.setCellType(Cell.CELL_TYPE_STRING);
            destCell.setCellValue(srcCell.getRichStringCellValue());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            destCell.setCellType(Cell.CELL_TYPE_NUMERIC);
            if (DateUtil.isCellDateFormatted(srcCell)) {
                destCell.setCellValue(srcCell.getDateCellValue());
            } else {
                destCell.setCellValue(srcCell.getNumericCellValue());
            }//from   ww  w  .j ava 2 s.co  m
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            destCell.setCellType(Cell.CELL_TYPE_BOOLEAN);
            destCell.setCellValue(srcCell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA:
            destCell.setCellType(Cell.CELL_TYPE_FORMULA);
            destCell.setCellValue(srcCell.getCellFormula());
            break;
        }
        copyXSSFCellStyle(srcCell, destCell);
    } else {
        throw new IllegalArgumentException("Cannot copy from / to null XSSFCell!");
    }
}

From source file:net.openchrom.xxd.processor.supplier.rscripting.ui.jobs.LoadXlsxExcelJob.java

License:Open Source License

private void loadExcel(final String file) {

    final File fil = new File(file);
    if (fil.exists()) {
        canRead = true;/* ww w  . j a v a2  s  .  com*/
        if (grid != null) {
            try {
                InputStream inp = new FileInputStream(file);
                try {
                    wb = new XSSFWorkbook(inp);
                } catch (Exception e) {
                    MsgDialog.message("Wrong format!\nOnly Excel *.xlsx (2007-2010) is supported!");
                    canRead = false;
                    e.printStackTrace();
                }
                // wb = new HSSFWorkbook(inp);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (canRead) {
                for (s = 0; s < wb.getNumberOfSheets(); s++) {
                    Display display = PlatformUI.getWorkbench().getDisplay();
                    display.syncExec(new Runnable() {

                        public void run() {

                            String name = fil.getName();
                            grid = new Spread().spread(SampleView.getTabFolder(), 0, 0, name);
                            SampleView.setGrid(grid);
                            XSSFSheet sheet = wb.getSheetAt(s);
                            int colCount = grid.getColumnCount();
                            int rowCount = grid.getItemCount();
                            int exelRow = endOfRow(sheet);
                            int exelColumn = endOfColumn(sheet);
                            // System.out.println(exelRow + " " + exelColumn
                            // + "---" + sheet.getPhysicalNumberOfRows() +
                            // " " +
                            // sheet.getRow(0).getPhysicalNumberOfCells());
                            if (colCount < exelColumn) {
                                int diff = exelColumn - colCount;
                                for (int i = 0; i < diff; i++) {
                                    GridColumn column = new GridColumn(grid, SWT.NONE);
                                    column.setText("C " + (i + 1 + colCount));
                                    column.setWidth(50);
                                }
                            }
                            if (rowCount < exelRow) {
                                int diff = exelRow - rowCount;
                                for (int i = 0; i < diff; i++) {
                                    new GridItem(grid, SWT.NONE).setHeight(16);
                                }
                            }
                            // Iterate over each row in the sheet
                            int rows = sheet.getPhysicalNumberOfRows();
                            for (int i = 0; i < exelRow; i++) {
                                XSSFRow row = sheet.getRow(i);
                                if (row == null) {
                                    for (int u = 0; u < exelColumn; u++) {
                                        grid.getItem(i).setText(u, " ");
                                    }
                                } else {
                                    for (int u = 0; u < exelColumn; u++) {
                                        XSSFCell cell = row.getCell(u);
                                        if (cell != null) {
                                            switch (cell.getCellType()) {
                                            case XSSFCell.CELL_TYPE_NUMERIC:
                                                String val = String.valueOf(cell.getNumericCellValue());
                                                grid.getItem(i).setText(u, val);
                                                break;
                                            case XSSFCell.CELL_TYPE_STRING:
                                                XSSFRichTextString st = cell.getRichStringCellValue();
                                                String val2 = st.getString();
                                                grid.getItem(i).setText(u, val2);
                                                break;
                                            case XSSFCell.CELL_TYPE_FORMULA:
                                                try {
                                                    String val3 = String.valueOf(cell.getRawValue());
                                                    grid.getItem(i).setText(u, val3);
                                                } catch (Exception e) {
                                                    // System.out.println(e.getMessage());
                                                    String s2 = cell.getCellFormula();
                                                    grid.getItem(i).setText(u, s2);
                                                }
                                                break;
                                            case XSSFCell.CELL_TYPE_BLANK:
                                                grid.getItem(i).setText(u, " ");
                                                break;
                                            case XSSFCell.CELL_TYPE_BOOLEAN:
                                                boolean s4 = cell.getBooleanCellValue();
                                                if (s4) {
                                                    grid.getItem(i).setText(u, "TRUE");
                                                } else {
                                                    grid.getItem(i).setText(u, "FALSE");
                                                }
                                                break;
                                            default:
                                                break;
                                            }
                                        } else {
                                            grid.getItem(i).setText(u, " ");
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
                wb = null;
            }
        }
    } else {
        MsgDialog.message("File not found!");
    }
}

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

License:Apache License

private void copyRow(XSSFRow sourceRow, XSSFRow targetRow, XSSFCreationHelper factory, XSSFDrawing patriarch) {
    for (int j = 0; j < sourceRow.getPhysicalNumberOfCells(); j++) {
        XSSFCell cell = sourceRow.getCell(j);
        if (cell != null) {
            XSSFCell newCell = targetRow.createCell(j);
            int cellType = cell.getCellType();
            newCell.setCellType(cellType);
            switch (cellType) {
            case XSSFCell.CELL_TYPE_BOOLEAN:
                newCell.setCellValue(cell.getBooleanCellValue());
                break;
            case XSSFCell.CELL_TYPE_ERROR:
                newCell.setCellErrorValue(cell.getErrorCellValue());
                break;
            case XSSFCell.CELL_TYPE_FORMULA:
                newCell.setCellFormula(cell.getCellFormula());
                break;
            case XSSFCell.CELL_TYPE_NUMERIC:
                newCell.setCellValue(cell.getNumericCellValue());
                break;
            case XSSFCell.CELL_TYPE_STRING:
                newCell.setCellValue(cell.getRichStringCellValue());
                break;
            default:
                newCell.setCellValue(formatter.formatCellValue(cell));
            }//from  w  ww  . j a  v  a 2 s  .c o  m
            if (cell.getCellComment() != null) {
                XSSFClientAnchor anchor = factory.createClientAnchor();
                anchor.setDx1(100);
                anchor.setDx2(100);
                anchor.setDy1(100);
                anchor.setDy2(100);
                anchor.setCol1(newCell.getColumnIndex());
                anchor.setCol2(newCell.getColumnIndex() + 4);
                anchor.setRow1(newCell.getRowIndex());
                anchor.setRow2(newCell.getRowIndex() + 4);
                anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);

                XSSFComment comment = patriarch.createCellComment(anchor);
                comment.setString(cell.getCellComment().getString());
                newCell.setCellComment(comment);
            }
            newCell.setCellStyle(cell.getCellStyle());
            newCell.getSheet().setColumnWidth(newCell.getColumnIndex(),
                    cell.getSheet().getColumnWidth(cell.getColumnIndex()));
        }
    }
}