在学习导入之前呢,首先得学会导出,如果不会导出的请转入我的另一篇文章,介绍导出的
https://blog.youkuaiyun.com/weixin_49100429/article/details/119214881?spm=1001.2014.3001.5501
导入是一般是需要模板的,毕竟一般情况下是需要和我们的数据库字段对应上,而模板就是导出需要做的事情。这里不废话,直接开始。
更多操作请参考官方文档http://poi.apache.org/components/spreadsheet/quick-guide.html
1.导入相关依赖
<!--excel表格 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
2.编写控制层
@PostMapping("importExcelMode")
public void importExcelMode(@RequestParam("file") MultipartFile file) {
try {
excelService.importExcelMode(file);
} catch (Exception e) {
e.printStackTrace();
}
}
3.写导出方法importExcelMode
public void importExcelMode(MultipartFile file){
InputStream inputStream =null;
Workbook workbook = null;
try {
//获取输入流
inputStream = file.getInputStream();
//获取工作空间
if (file.getOriginalFilename().endsWith(".xls")) {
workbook = new HSSFWorkbook(inputStream);
} else if (file.getOriginalFilename().endsWith(".xlsx")) {
workbook = new XSSFWorkbook(inputStream);
} else {
throw new IOException("文件格式不符合!");
}
//获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
//判断是否有工作表
if(sheet!=null){
//逐行遍历getLastRowNum表示最大行数
for (int i=0;i<=sheet.getLastRowNum();i++){
Row row = sheet.getRow(i);
//逐列遍历
for (int j=0;j<row.getLastCellNum();j++){
Cell cell = row.getCell(j);
//判断类型,然后根据类型输出结果
switch (cell.getCellTypeEnum()) {
//字符串
case STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
//数字的
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
//时间的
System.out.println(cell.getDateCellValue());
} else {
//数字的
System.out.println(cell.getNumericCellValue());
}
break;
//布尔的
case BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
//公式
case FORMULA:
System.out.println(cell.getCellFormula());
break;
//空白
case BLANK:
System.out.println();
break;
default:
System.out.println();
}
}
}
}
}catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.测试
输出结果:
5.总结
该篇中最好把他们封装成一个一个的工具类,比如获取工作空间封装一下,获取值也封装一下,不过这些都是基础,想要更多操作,比如获取合并单元格的请参考官方文档
http://poi.apache.org/components/spreadsheet/quick-guide.html