您的位置:首页 > 编程语言 > Java开发

Springboot 之 使用POI读取解析Excel文件

2016-10-28 23:21 375 查看
本文章来自【知识林】

在上一篇文章《Springboot 之 POI导出Word文件》中讲述了使用POI对Word的导出操作,这一篇将继续讲述POI的其他使用:对Excel表格的读写操作。

准备Excel源文件

这里简单准备了一个Excel表格,将此文件命名为:
web-info.xls
,放到
resources
目录下,内容如下图:



读取文件标题

//读取单个单元格
@Test
public void testRead() throws Exception {
//Excel文件
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(ResourceUtils.getFile("classpath:web-info.xls")));
//Excel工作表
HSSFSheet sheet = wb.getSheetAt(0);

//表头那一行
HSSFRow titleRow = sheet.getRow(0);

//表头那个单元格
HSSFCell titleCell = titleRow.getCell(0);

String title = titleCell.getStringCellValue();

System.out.println("标题是:"+title);
}


执行测试后将得到:
标题是:网站信息管理


将数据项读取到List中

准备一个DTO文件方便创建对象和输出内容

public class WebDto {

//网站名称
private String name;

//网址
private String url;

//用户名
private String username;

//密码
private String password;

//日均访问量
private Integer readCount;

public WebDto(String name, String url, String username, String password, Integer readCount) {
this.name = name;
this.url = url;
this.username = username;
this.password = password;
this.readCount = readCount;
}

public WebDto() {}

@Override
public String toString() {
return "WebDto{" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", readCount=" + readCount +
'}';
}
}


具体的测试方法:

//读取到列表
@Test
public void testReadList() throws Exception {
List<WebDto> list = new ArrayList<WebDto>();

HSSFWorkbook book = new HSSFWorkbook(new FileInputStream(ResourceUtils.getFile("classpath:web-info.xls")));

HSSFSheet sheet = book.getSheetAt(0);

for(int i=2; i<sheet.getLastRowNum()+1; i++) {
HSSFRow row = sheet.getRow(i);
String name = row.getCell(0).getStringCellValue(); //名称
String url = row.getCell(1).getStringCellValue(); //url
String username = row.getCell(2).getStringCellValue();
String password = row.getCell(3).getStringCellValue();
Integer readCount = (int) row.getCell(4).getNumericCellValue();

list.add(new WebDto(name, url, username, password, readCount));
}

System.out.println("共有 " + list.size() + " 条数据:");
for(WebDto wd : list) {
System.out.println(wd);
}
}


执行测试方法后将得到:

共有 2 条数据:
WebDto{name='知识林', url='http://www.zslin.com', username='admin', password='111111', readCount=500}
WebDto{name='用户管理', url='http://basic.zslin.com/admin', username='admin', password='111111', readCount=123}


示例代码:https://github.com/zsl131/spring-boot-test/tree/master/study15

本文章来自【知识林】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poi excel