SpringBoot导入excle文件数据学习记录
本文采用 了springboot环境下搭建的环境,处理采用前后端分离模式
亲测可用
导入包部分
<!-- 导入excel需要的包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
代码部分
// An highlighted block
@RequestMapping(value = "/uploadTest", method = RequestMethod.POST)
public String uploadTest(@RequestParam MultipartFile file, HttpServletRequest request) {
try {
System.out.println("进入到方法!");
if (file == null)
// return BaseCode.retCode(1, "上传文件不能为空").toString();
System.out.println("上传文件不能为空");
String fileName = file.getOriginalFilename();
System.out.println(fileName);
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
System.out.println("上传文件格式错误,请上传后缀为.xls或.xlsx的文件");
}
// xls是低版本的Excel文件
InputStream is = file.getInputStream();
Workbook wb = null;
if (fileName.endsWith(".xls")) {
wb = new HSSFWorkbook(is);
}
// xlsx是高版本的Excel文件
if (fileName.endsWith(".xlsx")) {
wb = new XSSFWorkbook(is);
}
System.out.println("xlsx的文档内容 :" + wb);
if (wb == null) {
throw new NullArgumentException();
}
//获取第一个工作表对象
Sheet sheet = wb.getSheetAt(0);
//这个对象不为空
if (sheet != null) {
//notNull = true;
}
// 获取所有行数
int rows = sheet.getLastRowNum();// 获取所有行数
System.out.println("总 行 数" + rows);
//获取表总列数
int col = sheet.getRow(0).getLastCellNum();
System.out.println("总 列 数" + col);
//循环遍历这个表格每一列
for (int r = 0; r < rows; r++) {
Row row = sheet.getRow(r);
System.out.println("-------------");
if (row == null) {
continue;
}
//列其实是可以 固定的 0 表示第几列 具体根据自己几列决定
//获得第一行第一列数据 getStringCellValue 字符串类型
if (row.getCell(0).getStringCellValue() != null) {
System.out.println(row.getCell(0).getStringCellValue());
}
//获得第一行第二列数据 getNumericCellValue 数字类型
if (row.getCell(1).getStringCellValue() != null) {
System.out.println(row.getCell(1).getNumericCellValue());
}
}
} catch (Exception e) {//IOException
System.out.println("捕获异常!");
}
System.out.println("打印完成");
return file.getName();
}
使用apipost调用上传文件
参考链接 https://www.cnblogs.com/owenma/p/10099060.html