版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010046908/article/details/50581867
最近做项目遇到了读取Excel数据到数据库做数据的初始化。于是找一个。发现(poi-3.13)可以解决问题。可以解析两种格式(xlsx和xls)
以下是实现的步骤
1.下载poi3.13包,地址(http://poi.apache.org/download.html#POI-3.13)
2.学习APi。
接下来是还是demo来说明问题吧:
1.准备Excel文件:
2.项目的目录结构:
代码实战:
/**
* 读取Excel数据
* @param file
*/
public List<Student> readExcel(File file){
List<Student> list = new ArrayList<Student>();
try {
InputStream inputStream = new FileInputStream(file);
String fileName = file.getName();
Workbook wb = null;
if(fileName.endsWith("xls")){
//解析xls格式
wb = new HSSFWorkbook(inputStream);
}else if(fileName.endsWith("xlsx")){
//解析xlsx格式
wb = new XSSFWorkbook(inputStream);
}
//第一个工作表
Sheet sheet = wb.getSheetAt(0);
//第一行的行号
int firstRowIndex = sheet.getFirstRowNum();
//最后一行的行号
int lastRowIndex = sheet.getLastRowNum();
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex ++){
//获取每一行
Row row = sheet.getRow(rIndex);
Student student = new Student();
if(row != null){
//获取第一例
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for(int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex ++){
switch (cIndex) {
case 0:
student.setNo1(row.getCell(0).toString());
break;
case 1:
student.setNo2(row.getCell(1).toString());
break;
case 2:
student.setNo3(row.getCell(2).toString());
break;
case 3:
student.setNo4(row.getCell(3).toString());
break;
case 4:
student.setNo5(row.getCell(4).toString());
break;
case 5:
student.setNo6(row.getCell(5).toString());
break;
case 6:
student.setNo7(row.getCell(6).toString());
break;
default:
break;
}
}
}
list.add(student);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
结果展示:
就这样了,有问题可以联系我QQ:1561281670