/**
* 文件读取是耗时操作,所以要放在线程中进行
* 因为子线程无法刷新主线程,所以要创建一个handler
* 用来刷新界面
*
* 资源读取两种方式:
* 1--本地SD卡读取
* 2--assets中读取
*
* 这里只读取第一列与第二列的数据
* 读取SD卡的excel资源可随意找一个,修改一下名字即可
*/
private void readExcel(){
new Thread(new Runnable() {
@Override
public void run() {
al = new ArrayList<HashMap<String,String>>();
InputStream is=null;
try {
//从SD卡读取
File file = new File(Environment.getExternalStorageDirectory(), "扫描类型.xls");//根目录下
is = new FileInputStream(file);
//从assets中读取
//AssetManager am=mContext.getAssets();
//is = am.open("data.xls");
Workbook wb = Workbook.getWorkbook(is);
Sheet sheet = wb.getSheet(0);
int row = sheet.getRows();
HashMap<String,String> hm;
for(int i=0; i<row; ++i) {
Cell cellarea = sheet.getCell(0, i);
Cell cellschool = sheet.getCell(1, i);
System.out.println(cellarea.getContents()+":"+cellschool.getContents());
hm = new HashMap<String,String>();
hm.put("AREA", cellarea.getContents());
hm.put("SCHOOL", cellschool.getContents());
al.add(hm);
}
mHandler.sendEmptyMessage(0x0001);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public Handler mHandler = new Handler(){
public void handleMessage(Message msg){
SimpleAdapter sa = new SimpleAdapter(mContext,al,R.layout.lv_item,new String[]{"AREA","SCHOOL"},new int[]{R.id.tv_area,R.id.tv_school});
lv.setAdapter(sa);
}
};//lv_item.xml适配器文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:id="@+id/tv_area" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="省份" /> <TextView android:id="@+id/tv_school" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="right" android:text="大学" /> </LinearLayout>
//main.xml布局文件,只有一个ListView <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>
//项目截图
PS:这个excel其实来自网上某位博友,我这里对齐做了下优化
1、把读取的耗时操作放在了线程里进行
2、增加了从SD卡读取资源
本文出自 “爬过山见过海” 博客,请务必保留此出处http://670176656.blog.51cto.com/4500575/1701069
原文地址:http://670176656.blog.51cto.com/4500575/1701069