生成文件
以下以下載excel文件為例,如有其它需要可自定義實現類繼承相應springmvc提供的試圖接口即可。
如生成Excel則繼承AbstractExcelView,生成PDF則繼承AbstractPdfView。
java代碼:
1 /*
2 * 導出用戶信息到EXCEL 3 * 4 * @return 5 */ 6 @RequestMapping(value = "/excel") 7 public ModelAndView exportExcel() { 8 ModelAndView mv = this.getModelAndView(); 9 PageData pd = new PageData(); 10 pd = this.getPageData(); 11 try { 12 13 // 檢索條件=== 14 String USERNAME = pd.getString("USERNAME"); 15 if (null != USERNAME && !"".equals(USERNAME)) { 16 USERNAME = USERNAME.trim(); 17 pd.put("USERNAME", USERNAME); 18 } 19 String lastLoginStart = pd.getString("lastLoginStart"); 20 String lastLoginEnd = pd.getString("lastLoginEnd"); 21 if (lastLoginStart != null && !"".equals(lastLoginStart)) { 22 lastLoginStart = lastLoginStart + " 00:00:00"; 23 pd.put("lastLoginStart", lastLoginStart); 24 } 25 if (lastLoginEnd != null && !"".equals(lastLoginEnd)) { 26 lastLoginEnd = lastLoginEnd + " 00:00:00"; 27 pd.put("lastLoginEnd", lastLoginEnd); 28 } 29 // 檢索條件=== 30 31 Map<String, Object> dataMap = new HashMap<String, Object>(); 32 List<String> titles = new ArrayList<String>(); 33 34 titles.add("用戶名"); // 1 35 titles.add("編號"); // 2 36 titles.add("姓名"); // 3 37 titles.add("職位"); // 4 38 titles.add("手機"); // 5 39 titles.add("郵箱"); // 6 40 titles.add("最近登錄"); // 7 41 titles.add("上次登錄IP"); // 8 42 43 dataMap.put("titles", titles); 44 45 List<PageData> userList = userService.listAllUser(pd); 46 List<PageData> varList = new ArrayList<PageData>(); 47 for (int i = 0; i < userList.size(); i++) { 48 PageData vpd = new PageData(); 49 vpd.put("var1", userList.get(i).getString("USERNAME")); // 1 50 vpd.put("var2", userList.get(i).getString("NUMBER")); // 2 51 vpd.put("var3", userList.get(i).getString("NAME")); // 3 52 vpd.put("var4", userList.get(i).getString("ROLE_NAME")); // 4 53 vpd.put("var5", userList.get(i).getString("PHONE")); // 5 54 vpd.put("var6", userList.get(i).getString("EMAIL")); // 6 55 vpd.put("var7", userList.get(i).getString("LAST_LOGIN")); // 7 56 vpd.put("var8", userList.get(i).getString("IP")); // 8 57 varList.add(vpd); 58 } 59 60 dataMap.put("varList", varList); 61 62 ObjectExcelView erv = new ObjectExcelView(); // 執行excel操作 63 64 mv = new ModelAndView(erv, dataMap); 65 } catch (Exception e) { 66 logger.error(e.toString(), e); 67 } 68 return mv; 69 }
返回視圖類代碼:
1 package com.fh.util;
2
3 import java.util.Date; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import org.apache.poi.hssf.usermodel.HSSFCell; 11 import org.apache.poi.hssf.usermodel.HSSFCellStyle; 12 import org.apache.poi.hssf.usermodel.HSSFFont; 13 import org.apache.poi.hssf.usermodel.HSSFSheet; 14 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 15 import org.springframework.web.servlet.view.document.AbstractExcelView; 16 17 18 /** 19 * 導入到EXCEL 類名稱:ObjectExcelView.java 20 * @author link 21 * 22 */ 23 public class ObjectExcelView extends AbstractExcelView { 24 25 @Override 26 protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, 27 HttpServletResponse response) throws Exception { 28 // TODO Auto-generated method stub 29 Date date = new Date(); 30 String filename = Tools.date2Str(date, "yyyyMMddHHmmss"); 31 HSSFSheet sheet; 32 HSSFCell cell; 33 response.setContentType("application/octet-stream"); 34 response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); 35 sheet = workbook.createSheet("sheet1"); 36 37 List<String> titles = (List<String>) model.get("titles"); 38 int len = titles.size(); 39 HSSFCellStyle headerStyle = workbook.createCellStyle(); // 標題樣式 40 headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 41 headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 42 HSSFFont headerFont = workbook.createFont(); // 標題字體 43 headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 44 headerFont.setFontHeightInPoints((short) 11); 45 headerStyle.setFont(headerFont); 46 short width = 20, height = 25 * 20; 47 sheet.setDefaultColumnWidth(width); 48 for (int i = 0; i < len; i++) { // 設置標題 49 String title = titles.get(i); 50 cell = getCell(sheet, 0, i); 51 cell.setCellStyle(headerStyle); 52 setText(cell, title); 53 } 54 sheet.getRow(0).setHeight(height); 55 56 HSSFCellStyle contentStyle = workbook.createCellStyle(); // 內容樣式 57 contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 58 List<PageData> varList = (List<PageData>) model.get("varList"); 59 int varCount = varList.size(); 60 for (int i = 0; i < varCount; i++) { 61 PageData vpd = varList.get(i); 62 for (int j = 0; j < len; j++) { 63 String varstr = vpd.getString("var" + (j + 1)) != null ? vpd.getString("var" + (j + 1)) : ""; 64 cell = getCell(sheet, i + 1, j); 65 cell.setCellStyle(contentStyle); 66 setText(cell, varstr); 67 } 68 } 69 } 70 }
文件上傳
springmvc配置文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 6 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 8 9 <!-- mvc:annotation-driven默認加載了url映射器和適配器 --> 10 <mvc:annotation-driven /> 11 <mvc:default-servlet-handler /> 12 13 <context:component-scan base-package="com.fh.controller" /> 14 <context:component-scan base-package="com.json" /> 15 16 <!-- 對靜態資源文件的訪問 restful --> 17 <mvc:resources mapping="/admin/**" location="/,/admin/" /> 18 <mvc:resources mapping="/static/**" location="/,/static/" /> 19 <mvc:resources mapping="/plugins/**" location="/,/plugins/" /> 20 <mvc:resources mapping="/uploadFiles/**" location="/,/uploadFiles/" /> 21 22 <!-- 訪問攔截 --> 23 <mvc:interceptors> 24 <mvc:interceptor> 25 <mvc:mapping path="/**/**" /> 26 <bean class="com.fh.interceptor.LoginHandlerInterceptor" /> 27 </mvc:interceptor> 28 </mvc:interceptors> 29 30 <!-- 配置SpringMVC的視圖解析器 --> 31 <bean 32 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 33 <property name="prefix" value="/WEB-INF/jsp/" /> 34 <property name="suffix" value=".jsp" /> 35 </bean> 36 37 <!-- 統一異常處理 --> 38 <bean id="exceptionResolver" class="com.fh.resolver.MyExceptionResolver"></bean> 39 40 <!-- 文件上傳 --> 41 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 42 <property name="maxUploadSize"> 43 <value>104857600</value> 44 </property> 45 <property name="maxInMemorySize"> 46 <value>4096</value> 47 </property> 48 <property name="defaultEncoding"> 49 <value>utf-8</value> 50 </property> 51 </bean> 52 </beans>
jsp代碼:
1 <form action="user/readExcel.do" name="Form" id="Form" method="post" enctype="multipart/form-data"> 2 <div id="zhongxin"> 3 <table style="width:95%;" > 4 5 <tr> 6 <td style="padding-top: 20px;"><input type="file" id="excel" name="excel" style="width:50px;" onchange="fileType(this)" /></td> 7 </tr> 8 <tr> 9 <td style="text-align: center;"> 10 <a class="btn btn-mini btn-primary" onclick="save();">導入</a> 11 <a class="btn btn-mini btn-danger" onclick="top.Dialog.close();">取消</a> 12 <a class="btn btn-mini btn-success" onclick="window.location.href='<%=basePath%>/user/downExcel.do'">下載模版</a> 13 </td> 14 </tr> 15 </table> 16 </div> 17 <div id="zhongxin2" class="center" style="display:none"><br/><img src="static/images/jzx.gif" /><br/><h4 class="lighter block green"></h4></div> 18 </form>
java代碼:
1 /** 2 * 從EXCEL導入到數據庫 3 */ 4 @RequestMapping(value = "/readExcel") 5 public ModelAndView readExcel(@RequestParam(value = "excel", required = false) MultipartFile file) 6 throws Exception { 7 ModelAndView mv = this.getModelAndView(); 8 PageData pd = new PageData(); 9 10 if (null != file && !file.isEmpty()) { 11 String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE; // 文件上傳路徑 12 String fileName = FileUpload.fileUp(file, filePath, "userexcel"); // 執行上傳 13 14 List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0); // 執行讀EXCEL操作,讀出的數據導入List 15 // 2:從第3行開始;0:從第A列開始;0:第0個sheet 16 17 /* 存入數據庫操作 */ 18 pd.put("RIGHTS", ""); // 權限 19 pd.put("LAST_LOGIN", ""); // 最后登錄時間 20 pd.put("IP", ""); // IP 21 pd.put("STATUS", "0"); // 狀態 22 pd.put("SKIN", "default"); // 默認皮膚 23 24 List<Role> roleList = roleService.listAllERRoles(); // 列出所有二級角色 25 26 pd.put("ROLE_ID", roleList.get(0).getROLE_ID()); // 設置角色ID為隨便第一個 27 /** 28 * var0 :編號 var1 :姓名 var2 :手機 var3 :郵箱 var4 :備注 29 */ 30 for (int i = 0; i < listPd.size(); i++) { 31 pd.put("USER_ID", this.get32UUID()); // ID 32 pd.put("NAME", listPd.get(i).getString("var1")); // 姓名 33 34 String USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1")); // 根據姓名漢字生成全拼 35 pd.put("USERNAME", USERNAME); 36 if (userService.findByUId(pd) != null) { // 判斷用戶名是否重復 37 USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1")) + Tools.getRandomNum(); 38 pd.put("USERNAME", USERNAME); 39 } 40 pd.put("BZ", listPd.get(i).getString("var4")); // 備注 41 if (Tools.checkEmail(listPd.get(i).getString("var3"))) { // 郵箱格式不對就跳過 42 pd.put("EMAIL", listPd.get(i).getString("var3")); 43 if (userService.findByUE(pd) != null) { // 郵箱已存在就跳過 44 continue; 45 } 46 } else { 47 continue; 48 } 49 50 pd.put("NUMBER", listPd.get(i).getString("var0")); // 編號已存在就跳過 51 pd.put("PHONE", listPd.get(i).getString("var2")); // 手機號 52 53 pd.put("PASSWORD", new SimpleHash("SHA-1", USERNAME, "123").toString()); // 默認密碼123 54 if (userService.findByUN(pd) != null) { 55 continue; 56 } 57 userService.saveU(pd); 58 } 59 /* 存入數據庫操作*/ 60 61 mv.addObject("msg", "success"); 62 } 63 64 mv.setViewName("save_result"); 65 return mv; 66 }