一、新建一个excel表格

二、新建一个java 工程导入 jxl-2.6.12.jar (用来解析excel的api)
三、新建一个相应的实体类 user
package cn.rebuild;
public class User {
private String name;
private String age;
private String address;
private String phone;
@Override
public String toString() {
return "[ name = " + name + ", age = " + age + ", address = " + address + ", phone = " + phone + " ]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
四、建一个读excel文件内容的类ReadFromExcel
package cn.rebuild;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class ReadFromExcel {
//定义实体的集合
public static List<User> list = new ArrayList<User>();
public static void readExcelFile(String filePath) {
try {
InputStream is = new FileInputStream(filePath);
Workbook rwb = Workbook.getWorkbook(is);
// 获得总的Sheets,得到sheet的层数
Sheet[] sheets = rwb.getSheets();
int sheetLen = sheets.length;
// 获得第一个Sheets 的结果
jxl.Sheet rs = rwb.getSheet(0);
int num_row = rs.getRows();
int num_column = rs.getColumns();
for (int j = 0; j < num_row; j++) {
User user = new User();
// 得到第j行的所有值
Cell[] cell = rs.getRow(j);
for (int column_index = 0; column_index < num_column; column_index++) {
// 得到第j行,第column_indexs列的值
String value = cell[column_index].getContents();
//System.out.print(value + " ");
//从第二行开始将值存入到实体里面并添加到list中
if (j >= 1) {
String columnValue = rs.getRow(j)[column_index].getContents();
switch(column_index){
case 1 : user.setName(columnValue);;break;
case 2 : user.setAge(columnValue);;break;
case 3 : user.setAddress(columnValue);;break;
case 4 : user.setPhone(columnValue);;break;
default : System.out.println("");break;
}
}
}
System.out.println("");
if (j >= 1) {
list.add(user);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
readExcelFile("d://temp/user.xls");
for(Iterator<User> it = list.iterator();it.hasNext();){
System.out.println(it.next().toString());
}
}
}
五、运行结果

原文:http://www.cnblogs.com/py1994/p/6901976.html