如何使用Spring MVC上传Excel文件?

时间:2018-11-12 10:37:37

标签: java excel spring-mvc file-upload

需要用于数据库集成(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";
}

1 个答案:

答案 0 :(得分:0)

要使用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>