POI实现Excel导入
一.思路
第一步: 将Excel表转换成List<ExcelDto> 其中 ExcelDto 属性全部设置成String (便于自定义注解正则校验)
第二步: 设置自定义注解(1:长度校验注解 2:正则校验注解 3:不能重复)
第三步:编写校验方法返回错误数据、错误数据list、 可导入数据list
第四步: 将可导入数据list导入数据库(涉及到相关数据库校验 例如:唯一性字段)
二.代码
1.导入依赖
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
2.工具类方法(请根据实际应用更改)
public static void getDataFromExcel(String filePath,int column) {
//判断是否为excel类型文件
if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx")) {
System.out.println("文件不是excel类型");
}
FileInputStream fis =null;
Workbook wookbook = null;
try {
//获取一个绝对地址的流
fis = new FileInputStream(filePath);
} catch(Exception e) {
e.printStackTrace();
}
try {
//2003版本的excel,用.xls结尾
wookbook = new HSSFWorkbook(fis);//得到工作簿
} catch (Exception ex) {
//ex.printStackTrace();
try {
//2007版本的excel,用.xlsx结尾
wookbook = new XSSFWorkbook(fis);//得到工作簿
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//得到一个工作表
Sheet sheet = wookbook.getSheetAt(0);
//获得表头
Row rowHead = sheet.getRow(0);
//判断表头是否正确
if(rowHead.getPhysicalNumberOfCells() != column) {
System.out.println("表头的数量不对!");
}
//获得数据的总行数
int totalRowNum = sheet.getLastRowNum();
//要获得属性
String on="";
String name = "";
String age = "";
//获得所有数据
for(int i = 1 ; i <= totalRowNum ; i++)
{
//获得第i行对象
Row row = sheet.getRow(i);
//获得获得第i行第0列
Cell cell = row.getCell((short)0);
on = cell.getStringCellValue();
//获得获得第i行第1列
cell = row.getCell((short)1);
name = cell.getStringCellValue();
//获得获得第i行第2列
cell = row.getCell((short)2);
age = cell.getStringCellValue();
System.out.println("编号:"+on+",名字:"+name+",年龄:"+age);
}
}
3.测试
@Test
public void t1(){
getDataFromExcel("D:\\下载\\人员档案列表.xls",3);
}
POI操作Excel文件的方法还有很多,也还有许多我不知道的方法,如果大家有时间可以一起研究。
POI网站:http://poi.apache.org/
POI API:http://poi.apache.org/apidocs/index.html
如果大家想浏览我的下一篇文章,请留言
版权声明:此文章属于原创,不准随意转载:https://blog.csdn.net/LYQ2332826438