首页>代码>spring boot多文件上传、单文件上传、Excel解析>/springboot-upload/src/main/java/com/simon/springbootupload/controller/SingleUploadController.java
package com.simon.springbootupload.controller; import com.simon.springbootupload.pojo.User; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author Simon */ @Controller public class SingleUploadController { private static final Logger logger = LoggerFactory.getLogger(SingleUploadController.class); @Value("${upload.savepath}") private String uploadPath; @GetMapping("/upload") @ResponseBody public String upload() { return "upload"; } /** * 测试简单的文件上传 * * @param file * @return */ @PostMapping("/upload") @ResponseBody public String uploadExcel(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "上传失败,请重新选择文件"; } String fileName = file.getOriginalFilename(); File dest = new File(uploadPath + UUID.randomUUID() + "-" + fileName); try { file.transferTo(dest); logger.info("文件上传成功"); return "上传成功"; } catch (Exception e) { logger.error("上传失败:{}", e.getMessage()); } return "上传失败"; } /** * 测试上传解析excel */ @ResponseBody @PostMapping("/parse/excel") public String parseExcel(@RequestParam("file") MultipartFile file) throws IOException { if (file.isEmpty()) { return "上传失败,请重新选择上传的文件"; } List<User> users = new ArrayList<>(); InputStream is = file.getInputStream(); HSSFWorkbook workbook = new HSSFWorkbook(is); HSSFSheet sheet01 = workbook.getSheetAt(0); for (Row row : sheet01) { if (row.getRowNum() < 2) { continue; } User user = new User(); user.setUsername(row.getCell(0).getStringCellValue()); user.setNo(row.getCell(1).getStringCellValue()); user.setHeight(new Double(row.getCell(2).getStringCellValue())); user.setAge(new Integer(row.getCell(3).getStringCellValue())); users.add(user); } return users.toString(); } }
最近下载更多
Seaskye LV14
2023年11月4日
lyh1989 LV34
2023年10月24日
镜影 LV2
2023年9月14日
做你的景天 LV7
2023年4月12日
lironggang LV38
2023年3月31日
jk-mack LV5
2023年2月19日
15908475644 LV4
2023年2月4日
快乐的程序员 LV25
2023年1月25日
最代码官方 LV167
2023年1月15日
最近浏览更多
vluobo LV1
3月19日
15103432984 LV2
3月17日
47795851 LV1
3月14日
heweimin LV12
3月8日
廖业贵 LV18
3月3日
1134116035
2月24日
暂无贡献等级
houxianzheng
2月19日
暂无贡献等级
woldxy LV12
2月19日
kkkllll LV2
1月23日
b5438b LV7
2023年12月20日