功能:使用Eclipse工具开发一个APP用于读取Excel文件并将其显示在手机上
【1】在layout布局中设置相关的组件属性(设置两个布局文件):
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_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/tv_address"
android:gravity="right"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
main.xml:
<?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/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
【2】把excel文件data.xls保存在assets文件中:
【3】读取excel文件需要导入包jxl.jar,将其保存到文件libs里;
【4】定义一个MainActivity继承Activity并实现度data.xls文件的读取显示操作:
MainActivity.java:
package com.yan.excelreader;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class MainActivity extends Activity {
private ListView lv;
private List<HashMap<String,String>> list ;
private HashMap<String,String> hash;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv=(ListView) findViewById(R.id.listView);
list=new ArrayList<HashMap<String,String>>();
//得到assets资源的对象
AssetManager as=this.getAssets();
InputStream in=null;
try {
//打开assets中的表data.xls
in=as.open("data.xls");
//获取文档
Workbook wb=Workbook.getWorkbook(in);
//获取工作薄
Sheet sheet=wb.getSheet(0);
int row=sheet.getRows();
for(int i=0;i<row;++i)
{
//获取每一个单元格的内容
Cell cellName=sheet.getCell(0, i);
Cell cellAddress=sheet.getCell(1, i);
System.out.println(cellName.getContents()+":"+cellAddress.getContents());
hash=new HashMap<String,String>();
hash.put("NAME", cellName.getContents());
hash.put("ADDRESS", cellAddress.getContents());
list.add(hash);
}
SimpleAdapter simple=new SimpleAdapter(this,list,R.layout.lv_item,
new String[]{"NAME","ADDRESS"},new int[]{R.id.tv_name,R.id.tv_address});
lv.setAdapter(simple);
} catch (Exception e) {
e.printStackTrace();
}
}
}
【5】程序运行结果为: