MultipartFile转File/HSSFWorkbook

原文链接:MultipartFile转File/HSSFWorkbook
在业务开发中遇见,通过上传Excel文件,解析并生成对应的数据。

1、什么是HttpServletRequest?

答:HttpServletResponse继承了ServletResponse接口,并提供了与Http协议有关的方法。

2、什么是MultipartFile?

答:MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。
3、引入文件包

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

4、转换类型

1、HttpServletRequest转MultipartHttpServletRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

2、MultipartHttpServletRequest转Map<String, MultipartFile>
Map<String, MultipartFile>fileMap =multipartRequest.getFileMap();

3、fileMap转MultipartFile
for(Map.Entry<String, MultipartFile> entity :fileMap.entrySet()){
    MultipartFile multipartFile = entity.getValue();
}

4、MultipartFile转file File
file =new File(multipartFile.getOriginalFilename());

5、MultipartFile转HSSFWorkbook HSSFWorkbook
workbook =new HSSFWorkbook(new POIFSFileSystem(multipartFile.getInputStream()));

以下连续记录数据HttpServletRequest转换为HSSFWorkbook(excel对象)

 @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        //request前端传回对象转换为 MultipartHttpServletRequest
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        //multipartRequest对象转换为Map的MultipartFile对象fileMap
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        //做单次循环,将MultipartFile对象解析出
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {

            //获取为MultipartFile对象multipartFile
            MultipartFile multipartFile = entity.getValue();

            //直接将MultipartFile强制转换为File文件
            File file = new File(multipartFile.getOriginalFilename());

            try {
                //将MultipartFile转换为HSSFWorkbook对象
                HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(multipartFile.getInputStream()));
                //这里获取了workbook对象便可对其进行excel操作。
            } catch (IOException e) {
                //
            }
        }
        return j;
    }

面向开发过程,记录学习之路。

你可能感兴趣的:(JAVA后端)