在面对选择国家地区,选择手机号码区号等信息的时候,常常我们是读取已存好的数据,我现在读取的就是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 {
//加载失败
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
说明
sheet.getCell(0, i).getContents() 表示第0行第1列的数据,因为事先是知道excel 表中的内容的,所以行和列自己定义就好了。
2.2 相关调用
new ExcelDataLoader().execute("phone_country_info.xls");
- 1
2.3 结果显示
转自:https://blog.csdn.net/android_freshman/article/details/53082304