现在的位置: 首页 > 综合 > 正文

利用jxl读取Excel的内容

2012年10月19日 ⁄ 综合 ⁄ 共 14780字 ⁄ 字号 评论关闭

利用jxl的jar包,读取excel中的内容。完整代码见附件,这里贴出来关键代码:

jxl的jar的版本信息:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.5.3
Created-By: 1.4.2_02-b03 (Sun Microsystems Inc.)
Main-Class: jxl.demo.Demo

1、 JHUserImportMgr代码如下:

/**
 * 从workbook中导入一个Excel信息
 *
 * @author rey2008
 *
 */
public class JHUserImportMgr {

    /**
     * 构造函数
     */
    public JHUserImportMgr() {
        super();
    }

    /**
     * 测试方法
     *
     * @param args
     * @throws WCMException
     * @throws Exception
     */
    public static void main(String[] args) throws WCMException, Exception {
        String sExcelPath = "D://test//test.xls";
        new JHUserImportMgr().importFromExcel(sExcelPath);
    }

    /**
     * 根据Excel所在物理路径导入当前组织和用户信息<BR>
     * 1.先导入组织信息的sheet <BR>
     * 2.再导入用户信息的sheet
     *
     * @param _sExcelFilePath
     *            excel路径
     * @throws WCMException
     * @throws Exception
     */
    public void importFromExcel(String _sExcelFilePath) throws WCMException,
            Exception {
        importFromExcel(_sExcelFilePath, "机构信息", "用户身份");
    }

    /**
     * 根据Excel所在物理路径导入当前组织和用户信息<BR>
     * 1.先导入组织信息的sheet <BR>
     * 2.再导入用户信息的sheet
     *
     * @param _sExcelFilePath
     *            excel路径
     * @param _sOrgSheetName
     *            机构信息所在sheet的名称
     * @param _sUserSheetName
     *            组织信息所在sheet的名称
     * @throws WCMException
     * @throws Exception
     */
    private void importFromExcel(String _sExcelFilePath, String _sOrgSheetName,
            String _sUserSheetName) throws WCMException, Exception {

        // 1. 同样支持.xlst格式,excel 2007
        if (_sExcelFilePath.indexOf(".xls") <= 0)
            throw new WCMException("文件不是Excel文件!");

        if (_sOrgSheetName == null || _sUserSheetName == null) {
            throw new WCMException("机构信息和用户信息所在的workSheet名称必须传入!");
        }

        // 2.判断文件是否存在
        File excelFile = new File(_sExcelFilePath);
        if (!excelFile.exists())
            throw new WCMException("路径[" + _sExcelFilePath + "]对应的文件不存在");

        // 3.定义Excel对象,即workbook
        Workbook book = Workbook.getWorkbook(excelFile);
        if (book == null) {
            throw new WCMException("获取文件[" + _sExcelFilePath
                    + "]的workbook对象失败!");
        }

        // 3. 获取所有workSheets
        Sheet[] allSheet = book.getSheets();

        // 4.遍历组织工作薄
        Sheet orgSheet = getSheetByName(allSheet, _sOrgSheetName);
        if (orgSheet == null) {
            throw new WCMException("机构的workSheet[名称=" + _sOrgSheetName
                    + "]不存在!");
        }
        OrgImport orgImport = new OrgImport();
        orgImport.importOrgFromSheet(orgSheet);

        // 5.遍历用户工作薄
        Sheet userSheet = getSheetByName(allSheet, _sUserSheetName);
        if (userSheet == null) {
            throw new WCMException("用户的workSheet[名称=" + _sUserSheetName
                    + "]不存在!");
        }
        UserImport userImport = new UserImport();
        userImport.importUserFromSheet(userSheet);
    }

    /**
     * 从指定的sheets集合中,查找指定名称的sheet对象,返回与指定名称匹配的第一个sheet对象
     *
     * @param _allSheet
     * @param _sSheetName
     * @return
     * @throws WCMException
     */
    private Sheet getSheetByName(Sheet[] _allSheet, String _sSheetName)
            throws WCMException {
        if (_allSheet == null || _sSheetName == null) {
            return null;
        }

        for (int i = 0; i < _allSheet.length; i++) {
            Sheet aSheet = _allSheet[i];
            if (aSheet == null) {
                continue;
            }

            // 根据名称匹配
            if (_sSheetName.equalsIgnoreCase(aSheet.getName())) {
                return aSheet;
            }
        }
        return null;
    }

 

2、 从excel中导入组织的类OrgImport代码如下:

/**
 * 机构导入类
 *
 * @author rey2008
 *
 */
public class OrgImport {

    /**
     * 构造函数
     */
    public OrgImport() {
        super();
    }

    /**
     * 从一个workSheet中读取用户信息
     *
     * @param _userSheet
     * @return
     * @throws WCMException
     */
    public boolean importOrgFromSheet(Sheet _orgSheet) throws WCMException {
        if (_orgSheet == null) {
            throw new WCMException("导入机构组织时,传入的sheet对象为null!");
        }

        int nSheetCount = _orgSheet.getRows();
        if (nSheetCount <= 1) {
            return false;// 机构sheet的第一行是字段
        }

        // 1.遍历行
        for (int i = 1; i < nSheetCount; i++) {

            // 获得一行的所有单元格
            Cell[] row = _orgSheet.getRow(i);
            String[] oneRowOrgInfo = new String[3];
            boolean bNeedSaveRow = false;// 是否需要保存该单元格

            // 遍历单元格内容
            for (int j = 0; j < row.length; j++) {

                // 最多读取前3列
                if (j >= 3) {
                    continue;
                }

                // 获得单元格内容
                String cellContent = row[j].getContents();

                // 如果单元格没有内容,则忽略
                if (cellContent == null || "".equals(cellContent)) {
                    continue;
                }

                // 赋值,并记录需要保存该单元格
                oneRowOrgInfo[j] = cellContent;
                bNeedSaveRow = true;
            }
            if (!bNeedSaveRow) {
                continue;
            }

            // 处理一行的机构数据
            doRealSave(oneRowOrgInfo);
        }

        return true;
    }

    /**
     * 根据从Exel中读取的组织信息,实现自己的业务逻辑。传入的数据结构为:new String[]{"一级组织","二级组织","三级组织"}
     *
     * @param _importUser
     *            大小为3的字符串数组,依次为"一级组织","二级组织","三级组织"
     * @return
     * @throws WCMException
     */
    private boolean doRealSave(String[] _organization) throws WCMException {
        System.out.println("_organization的数据:::::");
        System.out.println("0000==" + _organization[0]);
        System.out.println("11111==" + _organization[1]);
        System.out.println("2222==" + _organization[2]);

        return true;
    }

}

 

3、 从excel中导入用户的类UserImport代码如下:

/**
 * 用户导入类
 *
 * @author rey2008
 *
 */
public class UserImport {

    /**
     * 构造函数
     */
    public UserImport() {
        super();
    }

    /**
     * 从一个workSheet中读取用户信息
     *
     * @param _userSheet
     * @return
     * @throws WCMException
     */
    public boolean importUserFromSheet(Sheet _userSheet) throws WCMException {

        if (_userSheet == null) {
            throw new WCMException("导入机构组织时,传入的sheet对象为null!");
        }

        int nSheetCount = _userSheet.getRows();
        if (nSheetCount <= 1) {
            return false;// 用户身份sheet的第一行是字段
        }

        // 获取excel与内存对象的映射关系
        HashMap FieldsHashMap = getExcelFieldToUserFieldMap();

        // 获取excel列号与内存用户的字段映射关系
        HashMap columnToFieldMap = getColumnToField(_userSheet, FieldsHashMap);

        // 1.遍历行
        for (int i = 1; i < nSheetCount; i++) {

            // 获得一行的所有单元格
            Cell[] row = _userSheet.getRow(i);
            ImportUser aImportUser = new ImportUser();
            boolean bNeedSaveRow = false;// 是否需要保存该单元格

            // 遍历单元格内容
            for (int j = 0; j < row.length; j++) {

                // 获得单元格内容
                String cellContent = row[j].getContents();

                // 如果单元格没有内容,则忽略
                if (cellContent == null || "".equals(cellContent)) {
                    continue;
                }

                // 根据列号匹配出该列的名称
                Object oFieldNameInDB = columnToFieldMap.get(String.valueOf(j));
                if (oFieldNameInDB == null || "".equals(oFieldNameInDB))
                    continue;

                // 赋值,并记录需要保存该单元格
                setProperty(aImportUser, oFieldNameInDB.toString(), cellContent);
                bNeedSaveRow = true;
            }
            if (!bNeedSaveRow) {
                continue;
            }

            // 处理一行的用户信息数据
            doRealSave(aImportUser);
        }

        return true;
    }

    /**
     * 根据内存用户对象实现用户的真正导入逻辑
     *
     * @param _importUser
     *            从Excel中读取到的内存用户对象
     * @return
     * @throws WCMException
     */
    private boolean doRealSave(ImportUser _importUser) throws WCMException {

        System.out.println("************* begin  ***************");
        System.out.println("importUser.getLoginName=="
                + _importUser.getLoginName());
        System.out.println("importUser.getTrueName=="
                + _importUser.getTrueName());
        System.out.println("importUser.getTelephone=="
                + _importUser.getTelephone());
        System.out.println("importUser.getMobile==" + _importUser.getMobile());
        System.out.println("importUser.getEmail==" + _importUser.getEmail());
        System.out.println("importUser.getIsKM==" + _importUser.getIsKM());
        System.out.println("importUser.getIsKMExpert=="
                + _importUser.getIsKMExpert());
        System.out.println("importUser.getThirdOrganization=="
                + _importUser.getThirdOrganization());
        System.out.println("importUser.getSecondOrganization=="
                + _importUser.getSecondOrganization());
        System.out.println("importUser.getFirstOrganization=="
                + _importUser.getFirstOrganization());

        return true;
    }

    /**
     * 向一个内存用户对象设置一个属性
     *
     * @param _importUser
     * @param _sName
     * @param _sValue
     */
    private ImportUser setProperty(ImportUser _importUser, String _sName,
            String _sValue) {
        if ("LoginName".equalsIgnoreCase(_sName)) {
            _importUser.setLoginName(_sValue);
        } else if ("TrueName".equalsIgnoreCase(_sName)) {
            _importUser.setTrueName(_sValue);
        } else if ("Telephone".equalsIgnoreCase(_sName)) {
            _importUser.setTelephone(_sValue);
        } else if ("Mobile".equalsIgnoreCase(_sName)) {
            _importUser.setMobile(_sValue);
        } else if ("Email".equalsIgnoreCase(_sName)) {
            _importUser.setEmail(_sValue);
        } else if ("IsKM".equalsIgnoreCase(_sName)) {
            _importUser.setIsKM(convertToInt(_sValue));
        } else if ("IsKMExpert".equalsIgnoreCase(_sName)) {
            _importUser.setIsKMExpert(convertToInt(_sValue));
        } else if ("ThirdOrganization".equalsIgnoreCase(_sName)) {
            _importUser.setThirdOrganization(_sValue);
        } else if ("SecondOrganization".equalsIgnoreCase(_sName)) {
            _importUser.setSecondOrganization(_sValue);
        } else if ("FirstOrganization".equalsIgnoreCase(_sName)) {
            _importUser.setFirstOrganization(_sValue);
        }

        return _importUser;
    }

    /**
     * 把"是"转化为1,"否"转化为0
     *
     * @param _sValue
     * @return
     */
    private int convertToInt(String _sValue) {
        return "是".equalsIgnoreCase(_sValue) ? 1 : 0;
    }

    /**
     * 获取Excel文件的字段与内存对象中的字段映射关系
     *
     * @return
     */
    private HashMap getExcelFieldToUserFieldMap() {
        HashMap FieldsHashMap = new HashMap();
        FieldsHashMap.put("登录名", "LoginName");
        FieldsHashMap.put("用户真名", "TrueName");
        FieldsHashMap.put("电话号码", "Telephone");
        FieldsHashMap.put("手机", "Mobile");
        FieldsHashMap.put("EMAIL", "Email");
        FieldsHashMap.put("知识管理员", "IsKM");
        FieldsHashMap.put("知识专家", "IsKMExpert");
        FieldsHashMap.put("三级机构", "ThirdOrganization");
        FieldsHashMap.put("二级机构", "SecondOrganization");
        FieldsHashMap.put("一级机构", "FirstOrganization");
        return FieldsHashMap;
    }

    /**
     * 获取excel表中的列号与数据库中XWCMTopic表字段的映射关系
     *
     * @param _sheet
     * @param FieldsHashMap
     *            excel字段与内存用户对象字段的映射关系
     * @return
     * @throws WCMException
     */
    private HashMap getColumnToField(Sheet _sheet, HashMap FieldsHashMap)
            throws WCMException {

        if (_sheet == null) {
            throw new WCMException("传入的sheet对象为null!");
        }

        HashMap ColumnToFieldMap = new HashMap();

        // 获取excel中用户sheet的第一列,第一列定义了用户字段的信息标题
        int nRows = _sheet.getRows();
        if (nRows == 0)
            throw new WCMException("工作薄中必须含有第一行,第一行必须指定用户信息的基本字段!");

        // 获得第一行数据
        Cell[] row = _sheet.getRow(0);
        for (int j = 0; j < row.length; j++) {

            // 获得单元格内容,第一行指定了课题的字段,如"课题名称"
            String content = row[j].getContents();
            if (content == null || "".equals(content))
                continue;

            // 判断当前单元格内容是否是研究成果的基本信息字段
            Object oMapField = FieldsHashMap.get(content);
            if (oMapField == null || "".equals(oMapField))
                continue;

            // 列号与字段映射的hashMap添加记录
            ColumnToFieldMap.put(String.valueOf(j), oMapField);
        }

        return ColumnToFieldMap;
    }
}

 

4、 内存用户类ImportUser代码如下:

/**
 * Excel导入用户的内存类
 *
 * @author rey2008
 *
 */
public class ImportUser {

    /**
     * 构造函数
     */
    public ImportUser() {
        super();
    }

    // 成员变量===============================
    private String m_sLoginName = null;

    private String m_sTrueName = null;

    private String m_sTelephone = null;

    private String m_sMobile = null;

    private String m_sEmail = null;

    private String m_sLoginUserName = null;

    private int m_nIsKM = 0;// 0代表不是知识管理,1代表是知识管理

    private int m_nIsKMExpert = 0;// 0 代表不是知识专家,1代表是知识专家

    private String m_sThirdOrganization = null;

    private String m_sSecondOrganization = null;

    private String m_sFirstOrganization = null;

    // get 和set 方法 =========================================
    /**
     * @return the m_sLoginName
     */
    public String getLoginName() {
        return m_sLoginName;
    }

    /**
     * @param _sLoginName
     *            the m_sLoginName to set
     */
    public void setLoginName(String _sLoginName) {
        m_sLoginName = _sLoginName;
    }

    /**
     * @return the m_sTrueName
     */
    public String getTrueName() {
        return m_sTrueName;
    }

    /**
     * @param _sTrueName
     *            the m_sTrueName to set
     */
    public void setTrueName(String _sTrueName) {
        m_sTrueName = _sTrueName;
    }

    /**
     * @return the m_sTelephone
     */
    public String getTelephone() {
        return m_sTelephone;
    }

    /**
     * @param _sTelephone
     *            the m_sTelephone to set
     */
    public void setTelephone(String _sTelephone) {
        m_sTelephone = _sTelephone;
    }

    /**
     * @return the m_sMobile
     */
    public String getMobile() {
        return m_sMobile;
    }

    /**
     * @param _sMobile
     *            the m_sMobile to set
     */
    public void setMobile(String _sMobile) {
        m_sMobile = _sMobile;
    }

    /**
     * @return the m_sEmail
     */
    public String getEmail() {
        return m_sEmail;
    }

    /**
     * @param _sEmail
     *            the m_sEmail to set
     */
    public void setEmail(String _sEmail) {
        m_sEmail = _sEmail;
    }

    /**
     * @return the m_sLoginUserName
     */
    public String getLoginUserName() {
        return m_sLoginUserName;
    }

    /**
     * @param _loginUserName
     *            the m_sLoginUserName to set
     */
    public void setLoginUserName(String _loginUserName) {
        m_sLoginUserName = _loginUserName;
    }

    /**
     * @return the m_nIsKM
     */
    public int getIsKM() {
        return m_nIsKM;
    }

    /**
     * @param _nIsKM
     *            the m_nIsKM to set
     */
    public void setIsKM(int _nIsKM) {
        m_nIsKM = _nIsKM;
    }

    /**
     * @return the m_nIsKMExpert
     */
    public int getIsKMExpert() {
        return m_nIsKMExpert;
    }

    /**
     * @param nIsKMExpert
     *            the m_nIsKMExpert to set
     */
    public void setIsKMExpert(int nIsKMExpert) {
        m_nIsKMExpert = nIsKMExpert;
    }

    /**
     * @return the m_sThirdOrganization
     */
    public String getThirdOrganization() {
        return m_sThirdOrganization;
    }

    /**
     * @param _thirdOrganization
     *            the m_sThirdOrganization to set
     */
    public void setThirdOrganization(String _thirdOrganization) {
        m_sThirdOrganization = _thirdOrganization;
    }

    /**
     * @return the m_sSecondOrganization
     */
    public String getSecondOrganization() {
        return m_sSecondOrganization;
    }

    /**
     * @param _secondOrganization
     *            the m_sSecondOrganization to set
     */
    public void setSecondOrganization(String _secondOrganization) {
        m_sSecondOrganization = _secondOrganization;
    }

    /**
     * @return the m_sFirstOrganization
     */
    public String getFirstOrganization() {
        return m_sFirstOrganization;
    }

    /**
     * @param _firstOrganization
     *            the m_sFirstOrganization to set
     */
    public void setFirstOrganization(String _firstOrganization) {
        m_sFirstOrganization = _firstOrganization;
    }

}

抱歉!评论已关闭.