使用到的jar包
JSP: client.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <% String importMsg = ""; if (request.getSession().getAttribute("msg") != null) { importMsg = request.getSession().getAttribute("msg").toString(); } request.getSession().setAttribute("msg", ""); %> <head> <title>批量導入客戶</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js"></script> <script type="text/javascript"> function check() { var excel_file = $("#excel_file").val(); if (excel_file == "" || excel_file.length == 0) { alert("請選擇文件路徑!"); return false; } else { return true; } } $(document).ready(function() { var msg = ""; if ($("#importMsg").text() != null) { msg = $("#importMsg").text(); } if (msg != "") { alert(msg); } }); </script> <body> <a href="download.htm?fileName=muban.xls">下載Exel模板</a> <div> <font color="bule">批量導入客戶</font> </div> <form action="batchimport.htm" method="post" enctype="multipart/form-data" onsubmit="return check();"> <div style="margin: 30px;"> <input id="excel_file" type="file" name="filename" accept="xlsx" size="80" /> <input id="excel_button" type="submit" value="導入Excel" /> </div> <font id="importMsg" color="red"><%=importMsg%></font><input type="hidden" /> </form> </body> </html>
controller: ClientController.java
package com.shiliu.game.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.multipart.MultipartFile; import com.shiliu.game.domain.bean.Customer; import com.shiliu.game.utils.ReadExcel; import com.shiliu.game.utils.WDWUtil; /** * @author wkr * @Date 2016-11-18 */ @Controller @RequestMapping("/client") public class ClientController { private static Log log = LogFactory.getLog(ClientController.class); /** * 訪問controller進入操作頁面 * @return */ @RequestMapping(value="/init") public String init(){ System.out.println("控制台輸出:初始化頁面信息"); return "client/client"; } /** * 上傳Excel,讀取Excel中內容 * @param file * @param request * @param response * @return * @throws IOException */ @RequestMapping(value = "/batchimport",method = RequestMethod.POST) public String batchimport(@RequestParam(value="filename") MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws IOException{ log.info("ClientController ..batchimport() start"); String Msg =null; boolean b = false; //判斷文件是否為空 if(file==null){ Msg ="文件是為空!"; request.getSession().setAttribute("msg",Msg); return "client/client"; } //獲取文件名 String name=file.getOriginalFilename(); //進一步判斷文件是否為空(即判斷其大小是否為0或其名稱是否為null)驗證文件名是否合格 long size=file.getSize(); if(name==null || ("").equals(name) && size==0 && !WDWUtil.validateExcel(name)){ Msg ="文件格式不正確!請使用.xls或.xlsx后綴文檔。"; request.getSession().setAttribute("msg",Msg); return "client/client"; } //創建處理EXCEL ReadExcel readExcel=new ReadExcel(); //解析excel,獲取客戶信息集合。 List<Customer> customerList = readExcel.getExcelInfo(file); if(customerList != null && !customerList.toString().equals("[]") && customerList.size()>=1){ b = true; } if(b){ //迭代添加客戶信息(注:實際上這里也可以直接將customerList集合作為參數,在Mybatis的相應映射文件中使用foreach標簽進行批量添加。) for(Customer customer:customerList){ //這里可以做添加數據庫的功能 System.out.println("第一個值:"+customer.getCustomer1()+"\t第二個值:"+customer.getCustomer2()+"\t第三個值:"+customer.getCustomer3()); } Msg ="批量導入EXCEL成功!"; request.getSession().setAttribute("msg",Msg); }else{ Msg ="批量導入EXCEL失敗!"; request.getSession().setAttribute("msg",Msg); } return "client/client"; } /** * 下載Excel模板 * @param fileName * @param request * @param response * @return */ @RequestMapping("/download") public String download(String fileName, HttpServletRequest request, HttpServletResponse response) { System.out.println("控制台輸出:走入下載"); response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName="+ fileName); try { /*String path = Thread.currentThread().getContextClassLoader() .getResource("").getPath() + "download";//這個download目錄為啥建立在classes下的 */ String path="D:\\upload"; InputStream inputStream = new FileInputStream(new File(path+ File.separator + fileName)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } // 這里主要關閉。 os.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 返回值要注意,要不然就出現下面這句錯誤! //java+getOutputStream() has already been called for this response return null; } }
utils: WDWUtil.java
package com.shiliu.game.utils; /** * @author wkr * @Date 2016-11-18 * 工具類驗證Excel文檔 */ public class WDWUtil { /** * @描述:是否是2003的excel,返回true是2003 * @param filePath * @return */ public static boolean isExcel2003(String filePath) { return filePath.matches("^.+\\.(?i)(xls)$"); } /** * @描述:是否是2007的excel,返回true是2007 * @param filePath * @return */ public static boolean isExcel2007(String filePath) { return filePath.matches("^.+\\.(?i)(xlsx)$"); } /** * 驗證是否是EXCEL文件 * @param filePath * @return */ public static boolean validateExcel(String filePath){ if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){ return false; } return true; } }
utils: ReadExcel.java
package com.shiliu.game.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; 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.apache.poi.ss.usermodel.Workbook; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import com.shiliu.game.domain.bean.Customer; /** * @author wkr * @Date 2016-11-18 * 工具類讀取Excel類中內容 */ public class ReadExcel { //總行數 private int totalRows = 0; //總條數 private int totalCells = 0; //錯誤信息接收器 private String errorMsg; //構造方法 public ReadExcel(){} //獲取總行數 public int getTotalRows() { return totalRows;} //獲取總列數 public int getTotalCells() { return totalCells;} //獲取錯誤信息-暫時未用到暫時留着 public String getErrorInfo() { return errorMsg; } /** * 讀EXCEL文件,獲取客戶信息集合 * @param fielName * @return */ public List<Customer> getExcelInfo(MultipartFile Mfile){ //把spring文件上傳的MultipartFile轉換成CommonsMultipartFile類型 CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; //獲取本地存儲路徑 File file = new File("D:\\fileupload"); //創建一個目錄 (它的路徑名由當前 File 對象指定,包括任一必須的父路徑。) if (!file.exists()) file.mkdirs(); //新建一個文件 File file1 = new File("D:\\fileupload\\" + new Date().getTime() + ".xls"); //將上傳的文件寫入新建的文件中 try { cf.getFileItem().write(file1); } catch (Exception e) { e.printStackTrace(); } //初始化客戶信息的集合 List<Customer> customerList=new ArrayList<Customer>(); //初始化輸入流 FileInputStream is = null; Workbook wb = null; try{ //根據新建的文件實例化輸入流 is = new FileInputStream(file1); //根據excel里面的內容讀取客戶信息 //當excel是2003時 wb = new HSSFWorkbook(is); //當excel是2007時 //wb = new XSSFWorkbook(is); //讀取Excel里面客戶的信息 customerList=readExcelValue(wb); is.close(); }catch(Exception e){ e.printStackTrace(); } finally{ if(is !=null) { try{ is.close(); }catch(IOException e){ is = null; e.printStackTrace(); } } } return customerList; } /** * 讀取Excel里面客戶的信息 * @param wb * @return */ private List<Customer> readExcelValue(Workbook wb){ //得到第一個shell Sheet sheet=wb.getSheetAt(0); //得到Excel的行數 this.totalRows=sheet.getPhysicalNumberOfRows(); //得到Excel的列數(前提是有行數) if(totalRows>=1 && sheet.getRow(0) != null){//判斷行數大於一,並且第一行必須有標題(這里有bug若文件第一行沒值就完了) this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells(); }else{ return null; } List<Customer> customerList=new ArrayList<Customer>();//聲明一個對象集合 Customer customer;//聲明一個對象 //循環Excel行數,從第二行開始。標題不入庫 for(int r=1;r<totalRows;r++){ Row row = sheet.getRow(r); if (row == null) continue; customer = new Customer(); //循環Excel的列 for(int c = 0; c <this.totalCells; c++){ Cell cell = row.getCell(c); if (null != cell){ if(c==0){ customer.setCustomer1(getValue(cell));//得到行中第一個值 }else if(c==1){ customer.setCustomer2(getValue(cell));//得到行中第二個值 }else if(c==2){ customer.setCustomer3(getValue(cell));//得到行中第三個值 } } } //添加對象到集合中 customerList.add(customer); } return customerList; } /** * 得到Excel表中的值 * * @param cell * Excel中的每一個格子 * @return Excel中每一個格子中的值 */ @SuppressWarnings({ "static-access", "unused" }) private String getValue(Cell cell) { if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) { // 返回布爾類型的值 return String.valueOf(cell.getBooleanCellValue()); } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) { // 返回數值類型的值 return String.valueOf(cell.getNumericCellValue()); } else { // 返回字符串類型的值 return String.valueOf(cell.getStringCellValue()); } } }
entity: Customer.java

package com.shiliu.game.domain.bean; /** * @author wkr * @Date 2016-11-18 * 實體類 */ public class Customer { private Integer id; private String Customer1; private String Customer2; private String Customer3; public Customer() { super(); } public Customer(Integer id, String customer1, String customer2, String customer3) { super(); this.id = id; Customer1 = customer1; Customer2 = customer2; Customer3 = customer3; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCustomer1() { return Customer1; } public void setCustomer1(String customer1) { Customer1 = customer1; } public String getCustomer2() { return Customer2; } public void setCustomer2(String customer2) { Customer2 = customer2; } public String getCustomer3() { return Customer3; } public void setCustomer3(String customer3) { Customer3 = customer3; } }
效果頁面: