簡體   English   中英

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

[英]How to upload a Excel File By Using Spring MVC?

需要用於數據庫集成的代碼(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";
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM