1.首先我們先導(dǎo)入poi和文件上傳的依賴
- <!--POI-->
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml-schemas</artifactId>
- <version>3.14-beta1</version>
- </dependency>
- <!--文件上傳依賴-->
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
2.在spring-mvc.xml中配置文件上傳解析器
- <!-- 配置文件上傳解析器 -->
- <!-- id 的值是固定的-->
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 設(shè)置上傳文件的最大尺寸為 5MB -->
- <property name="maxUploadSize">
- <value>5242880</value>
- </property>
- </bean>
3.創(chuàng)建index.html
- <!-- excel文件導(dǎo)出 -->
- <p><a href="User/exportExcel.do" rel="external nofollow" >導(dǎo)出</a>
- <!-- excel文件導(dǎo)入 -->
- <form action="User/importExcel.do" method="post" enctype="multipart/form-data">
- <input type="file" name="userExcel" />
- <input type="submit" value="導(dǎo)入">
- </form>
4.創(chuàng)建實體類
- public class User {
- private Integer id;
- private String username;
- private String password;
- /* get 和 set */
- }
5.Controller層
- /**
- * 導(dǎo)出Excel
- * @param request
- * @param response
- */
- @RequestMapping("/exportExcel")
- @ResponseBody
- public void exportExcel(HttpServletRequest request, HttpServletResponse response){
- try {
- //獲取數(shù)據(jù)源
- List<User> userList = service.queryUserAll();
- //導(dǎo)出excel
- response.setHeader("Content-Disposition","attachment;filename="+new String("用戶信息.xls".getBytes(),"ISO-8859-1"));
- response.setContentType("application/x-excel;charset=UTF-8");
- OutputStream outputStream = response.getOutputStream();
- //導(dǎo)出
- service.exportExcel(userList,outputStream);
- outputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 導(dǎo)入exc
- * @param userExcel
- * @param request
- * @param session
- * @return
- */
- @RequestMapping("/importExcel")
- @ResponseBody
- public String importExcel(MultipartFile userExcel, HttpServletRequest request, HttpSession session) throws IOException, InvalidFormatException {
- if(userExcel == null){
- session.setAttribute("excelName", "未上傳文件,上傳失敗!");
- return null;
- }
- String userExcelFileName = userExcel.getOriginalFilename();
- if(!userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){
- session.setAttribute("excelName", "文件格式不正確!請使用.xls或.xlsx后綴的文檔,導(dǎo)入失敗!");
- return null;
- }
- //導(dǎo)入
- service.importExcel(userExcel);
- session.setAttribute("excelName", "導(dǎo)入成功!");
- return "redirect:queryUserAll.do";
- }
6.運行測試
1.點擊導(dǎo)出將數(shù)據(jù)庫的內(nèi)容以后綴為 .xls的文件下載下來
2. 選擇Excel文件點擊導(dǎo)入會將文件里的內(nèi)容導(dǎo)入到數(shù)據(jù)庫中
到此這篇關(guān)于SSM框架使用poi導(dǎo)入導(dǎo)出Excel的文章就介紹到這了,更多相關(guān)SSM框架導(dǎo)入導(dǎo)出Excel內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_51311866/article/details/115246070