SpringMVC下實現(xiàn)Excel文件上傳下載
在實際應(yīng)用中,經(jīng)常會遇到上傳Excel或者下載Excel的情況,比如導(dǎo)入數(shù)據(jù)、下載統(tǒng)計數(shù)據(jù)等等場景。針對這個問題,我寫了個基于SpringMVC的簡單上傳下載示例,其中Excel的處理使用Apache的POI組件。
主要依賴的包如下:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.10.1</version> </dependency>
相關(guān)處理類:
(一)Controller類
package com.research.spring.controller; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.research.spring.model.UserInfo; import com.research.spring.view.ExcelView; @Controller @RequestMapping("/file") public class FileController { /** * Excel文件上傳處理 * @param file * @return */ @RequestMapping("/upload") public ModelAndView uploadExcel(@RequestParam("file") MultipartFile file){ List<UserInfo> list = new ArrayList<UserInfo>(); //這里只處理文件名包括“用戶”的文件,模板使用下載模板 if( file.getOriginalFilename().contains("用戶") ){ try { Workbook wb = new HSSFWorkbook(file.getInputStream()); Sheet sheet = wb.getSheetAt(0); for( int i = 1; i <= sheet.getLastRowNum(); i++ ){ Row row = sheet.getRow(i); UserInfo info = new UserInfo(); info.setUserName(row.getCell(0).getStringCellValue()); info.setPassword(row.getCell(1).getStringCellValue()); list.add(info); } } catch (IOException e) { e.printStackTrace(); } } ModelAndView mav = new ModelAndView("content"); mav.addObject("content",list.toString()); return mav; } /** * Excel文件下載處理 */ @RequestMapping("/download") public ModelAndView downloanExcel(){ List<UserInfo> list = new ArrayList<UserInfo>(); UserInfo userInfo = new UserInfo(); userInfo.setPassword("0000"); userInfo.setUserName("sdfas"); list.add(userInfo); list.add(userInfo); list.add(userInfo); list.add(userInfo); Map<String,List<UserInfo>> map = new HashMap<String, List<UserInfo>>(); map.put("infoList", list); ExcelView ve = new ExcelView(); return new ModelAndView(ve,map); } }
(二)實體類
package com.research.spring.model; public class UserInfo { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "UserInfo [userName=" + userName + ", password=" + password + "]"; } }
(三)View類
這個類在下載時用到,在Spring渲染頁面時使用自定義的View類進行Excel的相關(guān)處理。
package com.research.spring.view; import java.io.OutputStream; import java.net.URLEncoder; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.springframework.web.servlet.view.document.AbstractExcelView; import com.research.spring.model.UserInfo; /** * 下載Excel視圖 * * @author wdmcygah * */ public class ExcelView extends AbstractExcelView { @Override protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { @SuppressWarnings("unchecked") List<UserInfo> list = (List<UserInfo>) model.get("infoList"); if (list != null && list.size() != 0) { int len = list.size(); Sheet sheet = workbook.createSheet(); // 第一行文字說明 Row row = sheet.createRow(0); Cell cell = row.createCell(0, Cell.CELL_TYPE_STRING); cell.setCellValue("用戶名"); cell = row.createCell(1, Cell.CELL_TYPE_STRING); cell.setCellValue("密碼"); //下面是具體內(nèi)容 for (int i = 0; i < len; i++) { row = sheet.createRow(i + 1); cell = row.createCell(0, Cell.CELL_TYPE_STRING); cell.setCellValue(list.get(i).getUserName()); cell = row.createCell(1, Cell.CELL_TYPE_STRING); cell.setCellValue(list.get(i).getPassword()); } } response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); //這里對文件名進行編碼,保證下載時漢字顯示正常 String fileName = URLEncoder.encode("用戶.xls", "utf-8"); //Content-disposition屬性設(shè)置成以附件方式進行下載 response.setHeader("Content-disposition", "attachment;filename=" + fileName); OutputStream os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); } }
(四)主要配置文件
上傳文件時需要在配置文件中配置MultipartResolver類,配置后Spring會自動將文件傳成MultipartFile對象,然后就可以進行相應(yīng)的處理。示例看Controller類。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <context:component-scan base-package="com.research" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 上傳文件解析器配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <!-- 上傳文件的大小限制 ,單位是字節(jié)--> <property name="maxUploadSize" value="5242880000000"></property> <!-- 上傳文件的臨時路徑,上傳完成后會自動刪除 --> <property name="uploadTempDir" value="upload/temp"></property> </bean> </beans>
(五)測試頁面
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <h3>測試下載Excel功能</h3> <form action="file/download.htm" enctype="multipart/form-data" method="post"> <input type="submit" value="下載Excel"></input> </form> <h3>測試上傳Excel功能</h3> <form action="file/upload.htm" enctype="multipart/form-data" method="post"> <input type="file" name="file"></input> <input type="submit" value="上傳Excel"></input> </form> </body> </html>
如果想看完整源碼,可以到我的Github倉庫查看。 其中,上傳文件只處理符合下載模板的文件。若要處理其它文件需要自實現(xiàn)。代碼測試通過無誤。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java日期工具類操作字符串Date和LocalDate互轉(zhuǎn)
這篇文章主要介紹了Java日期工具類操作字符串Date和LocalDate互轉(zhuǎn),文章首先通過需要先引入坐標展開主題的相關(guān)內(nèi)容介紹,需要的朋友可以參一下2022-06-06IDEA下創(chuàng)建SpringBoot+MyBatis+MySql項目實現(xiàn)動態(tài)登錄與注冊功能
這篇文章主要介紹了IDEA下創(chuàng)建SpringBoot+MyBatis+MySql項目實現(xiàn)動態(tài)登錄與注冊功能,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02SpringBoot中@Autowired爆紅原理分析及解決
這篇文章主要介紹了SpringBoot中@Autowired爆紅原理分析及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05request.getParameter()方法的簡單理解與運用方式
在JavaWeb開發(fā)中,request對象扮演著至關(guān)重要的角色,它是HTTP請求的封裝,request.getParameter()用于獲取客戶端通過GET或POST方式發(fā)送的參數(shù),與之相對,request.setAttribute()用于在服務(wù)器端設(shè)置屬性,這些屬性只在一次請求中有效2024-10-10Java實現(xiàn)等待所有子線程結(jié)束后再執(zhí)行一段代碼的方法
這篇文章主要介紹了Java實現(xiàn)等待所有子線程結(jié)束后再執(zhí)行一段代碼的方法,涉及java多線程的線程等待與執(zhí)行等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08Spring Boot+Jpa多數(shù)據(jù)源配置的完整步驟
這篇文章主要給大家介紹了關(guān)于Spring Boot+Jpa多數(shù)據(jù)源配置的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01mybatis-plus 如何判斷參數(shù)是否為空并作為查詢條件
這篇文章主要介紹了mybatis-plus 如何判斷參數(shù)是否為空并作為查詢條件,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03