关于Excel的导入和解析,我这边是针对后缀为.xls做了一个总结。
pom.xml中需要注入的依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!--Excel后缀为xls需要导入的依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
实体类:
public class User {
private String name;
private String age;
private String sex;
private String 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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", sex=" + sex + ", phone=" + phone + "]";
}
}
测试类:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class Test {
public static void main(String[] args) {
File file=new File("本地路径+excel文件名.xlsx");
User u = new User();
List<User> list=new ArrayList<User>();
try { //表
HSSFWorkbook workbook=new HSSFWorkbook(FileUtils.openInputStream(file));
HSSFSheet sheet=workbook.getSheetAt(0);
int firstRowNum=0;//设置开始开始读取的行
int lastRowNum=sheet.getLastRowNum();//最后一行有数据的行数
for(int i=firstRowNum;i<=lastRowNum;i++) {//行(循环)
HSSFRow row=sheet.getRow(i);
int lastCellNum=row.getLastCellNum();//最后一列有数据的列数
for(int j=0;j<lastCellNum;j++) {//列(循环)
HSSFCell cell=row.getCell(j);//当前单元格的数据
String value=cell.getStringCellValue();//将读取到的数据转换为String类型
if(i==0) {
u.setName(value);
}else if(i==1) {
u.setAge(value);
}else if(i>=2) {
u.setSex(sheet.getRow(i).getCell(0).getStringCellValue());
u.setPhone(sheet.getRow(i).getCell(1).getStringCellValue());
}
System.out.print(value+" ");
}
System.out.println();
list.add(u);
}
} catch (Exception e) {
e.printStackTrace();
}
for(User temp:list) {
System.out.println(temp);
}
}
}
excel格式:
第一行第一列 | 第一行第二列 |
第二行第一列 | 第二行第2列 |
第三行第一列 | 第三行第2列 |
Test.java输出结果如下:
第一行第一列 第一行第二列
第二行第一列 第二行第2列
第三行第一列 第三行第2列
User [name=第一行第二列, age=第二行第2列, sex=第三行第一列, phone=第三行第2列]
User [name=第一行第二列, age=第二行第2列, sex=第三行第一列, phone=第三行第2列]
User [name=第一行第二列, age=第二行第2列, sex=第三行第一列, phone=第三行第2列]