Android 读取excel 文件

在面对选择国家地区,选择手机号码区号等信息的时候,常常我们是读取已存好的数据,我现在读取的就是excel里面的数据,所以在此记录下读取的方法以及注意点。 
下面就是读取国际地区手机区号的数据效果图:

读取excel 效果图

excel表格里面数据

excel表格里面数据


1.准备工作

1.1 excel 表格 
我在assets 下放的的excel 表

1.2 读取excel 需要的jar 包

下载地址:jxl 读取excel 需要的jar 包

这里写图片描述

注意点: 
assets 的目录不要建错,他是在main 级别目录下的,建错地方会读取不到文件。

2.相关代码

2.1 读取excel

/**
     * 获取 excel 表格中的数据,不能在主线程中调用
     *
     * @param xlsName excel 表格的名称
     * @param index   第几张表格中的数据
     */
    private ArrayList<CountryModel> getXlsData(String xlsName, int index) {
        ArrayList<CountryModel> countryList = new ArrayList<CountryModel>();
        AssetManager assetManager = getAssets();

        try {
            Workbook workbook = Workbook.getWorkbook(assetManager.open(xlsName));
            Sheet sheet = workbook.getSheet(index);

            int sheetNum = workbook.getNumberOfSheets();
            int sheetRows = sheet.getRows();
            int sheetColumns = sheet.getColumns();

            Log.d(TAG, "the num of sheets is " + sheetNum);
            Log.d(TAG, "the name of sheet is  " + sheet.getName());
            Log.d(TAG, "total rows is 行=" + sheetRows);
            Log.d(TAG, "total cols is 列=" + sheetColumns);

            for (int i = 0; i < sheetRows; i++) {
                CountryModel countryModel = new CountryModel();
                countryModel.setChinaName(sheet.getCell(0, i).getContents());
                countryModel.setEnglishName(sheet.getCell(1, i).getContents());
                countryModel.setAreaNumber(sheet.getCell(2, i).getContents());

                countryList.add(countryModel);
            }

            workbook.close();

        } catch (Exception e) {
            Log.e(TAG, "read error=" + e, e);
        }

        return countryList;
    }


//在异步方法中 调用
private class ExcelDataLoader extends AsyncTask<String, Void, ArrayList<CountryModel>> {

        @Override
        protected void onPreExecute() {
            progressDialog.setMessage("加载中,请稍后......");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }

        @Override
        protected ArrayList<CountryModel> doInBackground(String... params) {
            return getXlsData(params[0], 0);
        }

        @Override
        protected void onPostExecute(ArrayList<CountryModel> countryModels) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            if(countryModels != null && countryModels.size()>0){
                //存在数据
                sortByName(countryModels);
                setupData(countryModels);
            }else {
                //加载失败


            }

        }
    }
说明 
sheet.getCell(0, i).getContents() 表示第0行第1列的数据,因为事先是知道excel 表中的内容的,所以行和列自己定义就好了。

2.2 相关调用

 new ExcelDataLoader().execute("phone_country_info.xls");

2.3 结果显示

这里写图片描述

猜你喜欢

转载自www.cnblogs.com/zhujiabin/p/9104619.html