目录
一、文件上传
1.创建一个 LogService,先实现文件上传功能服务
2.创建一个控制器LogController
3.然后我们就可以启动项目,访问对应的url。
二、下载
1.在LogService文件基础上,新增logDownload方法
2.在LogController文件基础上,新增logDownload方法
3.访问下载url
三、解析xls文件
1.导入poi.jar包
2.创建一个解析xls的工具类
3.使用HandleFile工具类
3.改造一下LogService.upLogLoad方法,实现文件上传+文件解析
4.最后启动服务,再上传一次文件
结果就大功告成。
工作上我们经常会遇到,数据导入数据库,或者报表导出。这期,我就到大家用springboot实现“文件上传+下载+解析"xls"文件”。
一、文件上传
1.创建一个 LogService,先实现文件上传功能服务
@Service
public class LogService {
public ResultVo upLogLoad(MultipartFile file) throws Exception {
if (file == null || file.isEmpty()) {
return ResultVo.error(1, "未选择需上传的日志文件");
}
//获取绝对路径
String filePath = new File("src/main/java/com/example/thyy/file").getAbsolutePath();
//获取文件名
String fileName = file.getOriginalFilename();
//判断文件类型,这里我们只要xls文件
if (fileName != null && !fileName.endsWith(".xls"))
return ResultVo.error(1, "请选择“xls”文件");
//获取文件上传名称
File fileUpload = new File(filePath, fileName);
if (fileUpload.exists()) {
return ResultVo.error(1, "上传的日志文件已存在");
}
try {
//上传文件
file.transferTo(fileUpload);
return ResultVo.success();
} catch (IOException e) {
return ResultVo.error(1, "上传日志文件到服务器失败" + e.toString());
}
}
}
@Service
public class LogService {
public ResultVo upLogLoad(MultipartFile file) throws Exception {
if (file == null || file.isEmpty()) {
return ResultVo.error(1, "未选择需上传的日志文件");
}
//获取绝对路径
String filePath = new File("src/main/java/com/example/thyy/file").getAbsolutePath();
//获取文件名
String fileName = file.getOriginalFilename();
//判断文件类型,这里我们只要xls文件
if (fileName != null && !fileName.endsWith(".xls"))
return ResultVo.error(1, "请选择“xls”文件");
//获取文件上传名称
File fileUpload = new File(filePath, fileName);
if (fileUpload.exists()) {
return ResultVo.error(1, "上传的日志文件已存在");
}
try {
//上传文件
file.transferTo(fileUpload);
return ResultVo.success();
} catch (IOException e) {
return ResultVo.error(1, "上传日志文件到服务器失败" + e.toString());
}
}
}
注意:filePath是指上传的文件,存到那个目录上。我这里我只写相对路径,然后后在通过File.getAbsolutePath()获取文件全路径。
2.创建一个控制器LogController
RestController
@RequestMapping("/log")
public class LogController {
@Autowired
LogService logService;
@PostMapping(value = "/upload")
public ResultVo logUpload(@RequestParam("file") MultipartFile file) throws Exception {
return logService.upLogLoad(file);
}
}
3.然后我们就可以启动项目,访问对应的url。
我用postman测试如下
然后就能看到我们上传的文件了
二、下载
1.在LogService文件基础上,新增logDownload方法
public ResultVo logDownload(String name, HttpServletResponse response) throws Exception {
//根据name,找到文件目录下,对应的文件
File file = new File("src/main/java/com/example/thyy/file/" + File.separator + name);
if (!file.exists()) {
return ResultVo.error(1, name + "文件不存在");
}
// 声明传输的内内容类型
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + name);
byte[] buffer = new byte[1024];
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)) {
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
}
return ResultVo.success();
}
2.在LogController文件基础上,新增logDownload方法
@GetMapping(value = "/downlod/{name}")
public ResultVo logDownload(@PathVariable String name, HttpServletResponse response) throws Exception {
return logService.logDownload(name, response);
}
3.访问下载url
public ResultVo logDownload(String name, HttpServletResponse response) throws Exception {
//根据name,找到文件目录下,对应的文件
File file = new File("src/main/java/com/example/thyy/file/" + File.separator + name);
if (!file.exists()) {
return ResultVo.error(1, name + "文件不存在");
}
// 声明传输的内内容类型
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + name);
byte[] buffer = new byte[1024];
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)) {
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
}
return ResultVo.success();
}
2.在LogController文件基础上,新增logDownload方法
@GetMapping(value = "/downlod/{name}")
public ResultVo logDownload(@PathVariable String name, HttpServletResponse response) throws Exception {
return logService.logDownload(name, response);
}
3.访问下载url
url正确时
url错误时
注意:在下载URL后加上我们要下载的文件名。
三、解析xls文件
1.导入poi.jar包
org.apache.poi
poi
3.9
org.apache.poi
poi-ooxml
3.9
org.apache.poi poi3.9 org.apache.poi poi-ooxml3.9
为方便写测试,再httpclient包
org.apache.httpcomponents httpclient4.5.6
2.创建一个解析xls的工具类
public class HandleFile{
public static List> parseExcel(InputStream in, String fileName) throws Exception {
List list = null;
Workbook work = null;
list = new ArrayList<>();
//创建Excel工作薄
work = getWorkbook(in, fileName);
if (null == work) {
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if (row == null || row.getFirstCellNum() == j) {
continue;
}
List
3.使用HandleFile工具类
- > parseExcel(InputStream in, String fileName) throws Exception {
List list = null;
Workbook work = null;
list = new ArrayList<>();
//创建Excel工作薄
work = getWorkbook(in, fileName);
if (null == work) {
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if (row == null || row.getFirstCellNum() == j) {
continue;
}
List
写个测试类
@Test
public void testExel() throws Exception {
// File file= new File("C:/Users/Administrator/documents/新建 XLS 工作表.xls");
File file = new File("C:/Users/Administrator/documents/Tencent Files/229068393/FileRecv/202110-205.xlsx");
if (!file.exists()) {
throw new Exception("不存在文件");
}
try {
FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("copy" + file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
InputStream inputStream = multipartFile.getInputStream();
//将文件的所有数据处理成了List> list
List> list = HandleFile.parseExcel(inputStream, multipartFile.getOriginalFilename());
inputStream.close();
for (int i = 0; i < list.size(); i++) {
List
注意:file是我们要解析的文件的路径
然后我们就得到了文件的内容了
3.改造一下LogService.upLogLoad方法,实现文件上传+文件解析
public ResultVo upLogLoad(MultipartFile file) throws Exception {
if (file == null || file.isEmpty()) {
return ResultVo.error(1, "未选择需上传的日志文件");
}
//获取绝对路径
String filePath = new File("src/main/java/com/example/springboot4/file").getAbsolutePath();
//获取上传时文件名
String fileName = file.getOriginalFilename();
//判断文件类型,这里我们只要xls文件
if (fileName != null && !fileName.endsWith(".xls"))
return ResultVo.error(1, "请选择“xls”文件");
//获取文件上传名称
File fileUpload = new File(filePath, fileName);
if (fileUpload.exists()) {
return ResultVo.error(1, "上传的日志文件已存在");
}
//改造start
InputStream inputStream = file.getInputStream();
List> list = HandleFile.parseExcel(inputStream, file.getOriginalFilename());
inputStream.close();
for (int i = 0; i < list.size(); i++) {
List
4.最后启动服务,再上传一次文件
- > list = HandleFile.parseExcel(inputStream, file.getOriginalFilename());
inputStream.close();
for (int i = 0; i < list.size(); i++) {
List



