【问题标题】:How to upload a Excel File By Using Spring MVC?如何使用 Spring MVC 上传 Excel 文件?
【发布时间】:2019-04-15 01:38:25
【问题描述】:

需要用于数据库集成(CRUD 操作)的代码

如何使用 Spring MVC 上传 Excel 文件? MultipartFile 类提供对上传文件的详细信息的访问,包括文件名、文件类型等。我们可以使用一个简单的 HTML 页面来显示这些信息:

我们还可以将附加信息与正在上传的文件一起发送到服务器。我们只需在表单中包含必填字段:

FileUploadService.java

public class FileUploadService {

@Autowired
FileUploadDao fileUploadDao;

public String uploadFileData(String inputFilePath){
    Workbook workbook = null;
        Sheet sheet = null;
        try 
        {

            workbook = getWorkBook(new File(inputFilePath));
            sheet = workbook.getSheetAt(0);

            /*Build the header portion of the Output File*/
            String headerDetails= "EmployeeId,EmployeeName,Address,Country";
            String headerNames[] = headerDetails.split(",");

             /*Read and process each Row*/
             ArrayList<ExcelTemplateVO> employeeList = new ArrayList<>();
             Iterator<Row> rowIterator = sheet.iterator();

             while(rowIterator.hasNext()) 
             {
                    Row row = rowIterator.next();
                    //Read and process each column in row
                    ExcelTemplateVO excelTemplateVO = new ExcelTemplateVO();
                    int count=0;
                    while(count<headerNames.length){
                        String methodName = "set"+headerNames[count];
                        String inputCellValue = getCellValueBasedOnCellType(row,count++);
                        setValueIntoObject(excelTemplateVO, ExcelTemplateVO.class, methodName, "java.lang.String", inputCellValue);
                    }

                    employeeList.add(excelTemplateVO);
             }
             fileUploadDao.saveFileDataInDB(employeeList);

        }
        catch(Exception ex){
            ex.printStackTrace();
        }


    return "Success";
}

【问题讨论】:

    标签: java excel spring-mvc file-upload


    【解决方案1】:

    要使用 spring mvc 上传 xls 文件,您可以编写如下的 spring 控制器,

    package com.journaldev.spring.controller;
    
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    /**
     * Handles requests for the application file upload requests
     */
    @Controller
    public class FileUploadController {
    
        private static final Logger logger = LoggerFactory
                .getLogger(FileUploadController.class);
    
        /**
         * Upload single file using Spring Controller
         */
        @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
        public @ResponseBody
        String uploadFileHandler(@RequestParam("name") String name,
                @RequestParam("file") MultipartFile file) {
    
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
    
                    // Creating the directory to store file
                    String rootPath = System.getProperty("catalina.home");
                    File dir = new File(rootPath + File.separator + "tmpFiles");
                    if (!dir.exists())
                        dir.mkdirs();
    
                    // Create the file on server
                    File serverFile = new File(dir.getAbsolutePath()
                            + File.separator + name);
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
    
                    logger.info("Server File Location="
                            + serverFile.getAbsolutePath());
    
                    return "You successfully uploaded file=" + name;
                } catch (Exception e) {
                    return "You failed to upload " + name + " => " + e.getMessage();
                }
            } else {
                return "You failed to upload " + name
                        + " because the file was empty.";
            }
        }
    
        /**
         * Upload multiple file using Spring Controller
         */
        @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
        public @ResponseBody
        String uploadMultipleFileHandler(@RequestParam("name") String[] names,
                @RequestParam("file") MultipartFile[] files) {
    
            if (files.length != names.length)
                return "Mandatory information missing";
    
            String message = "";
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String name = names[i];
                try {
                    byte[] bytes = file.getBytes();
    
                    // Creating the directory to store file
                    String rootPath = System.getProperty("catalina.home");
                    File dir = new File(rootPath + File.separator + "tmpFiles");
                    if (!dir.exists())
                        dir.mkdirs();
    
                    // Create the file on server
                    File serverFile = new File(dir.getAbsolutePath()
                            + File.separator + name);
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
    
                    logger.info("Server File Location="
                            + serverFile.getAbsolutePath());
    
                    message = message + "You successfully uploaded file=" + name
                            + "<br />";
                } catch (Exception e) {
                    return "You failed to upload " + name + " => " + e.getMessage();
                }
            }
            return message;
        }
    }
    

    您可以根据需要进行所有必需的验证,例如文件大小、文件类型等。

    你的 jsp 文件可能是这样的,

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ page session="false" %>
    <html>
    <head>
    <title>Upload Multiple File Request Page</title>
    </head>
    <body>
        <form method="POST" action="uploadMultipleFile" enctype="multipart/form-data">
            File1 to upload: <input type="file" name="file"><br /> 
            Name1: <input type="text" name="name"><br /> <br /> 
            File2 to upload: <input type="file" name="file"><br /> 
            Name2: <input type="text" name="name"><br /> <br />
            <input type="submit" value="Upload"> Press here to upload the file!
        </form>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2011-11-06
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多