springMVC从上传的Excel文件中读取数据

来源:互联网 发布:淘宝店铺招牌怎么上传 编辑:程序博客网 时间:2024/05/10 21:31

示例:导入客户文件(Excle文件)

一、编辑customer.xlsx

二、在spring的xml文件设置上传文件大小

<!-- 上传文件拦截,设置最大上传文件大小   10M=10*1024*1024(B)=10485760 bytes -->  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">      <property name="maxUploadSize" value="10485760" />  </bean>

三、编辑jsp(addCustomer3.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"> <body>      <div><font color="bule">批量导入客户</font></div>     <form action="addController/batchimport" 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> <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></html>
复制代码

四、编辑Java文件

4.1 控制器代码(AddController.java)

复制代码
@Controller@RequestMapping("toPage/addController/")public class AddController {        private static Log log = LogFactory.getLog(AddController.class);     @Autowired     private CustomerService customerService;          @RequestMapping(value = "batchimport", method = RequestMethod.POST)     public String batchimport(@RequestParam(value="filename") MultipartFile file,             HttpServletRequest request,HttpServletResponse response) throws IOException{         log.info("AddController ..batchimport() start");         //判断文件是否为空         if(file==null) return null;         //获取文件名         String name=file.getOriginalFilename();         //进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)         long size=file.getSize();         if(name==null || ("").equals(name) && size==0) return null;                  //批量导入。参数:文件名,文件。         boolean b = customerService.batchImport(name,file);         if(b){              String Msg ="批量导入EXCEL成功!";              request.getSession().setAttribute("msg",Msg);             }else{              String Msg ="批量导入EXCEL失败!";              request.getSession().setAttribute("msg",Msg);         }         return "Customer/addCustomer3";     }         }
复制代码

4.2 服务层代码(CustomerService.java),即上述方法中 customerService.batchImport(name,file);语句所调用的方法

复制代码
   //批量导入客户    public boolean batchImport(String name,MultipartFile file){        boolean b = false;        //创建处理EXCEL        ReadExcel readExcel=new ReadExcel();        //解析excel,获取客户信息集合。        List<Customer> customerList = readExcel.getExcelInfo(name ,file);        if(customerList != null){            b = true;        }                //迭代添加客户信息(注:实际上这里也可以直接将customerList集合作为参数,在Mybatis的相应映射文件中使用foreach标签进行批量添加。)        for(Customer customer:customerList){            customerDoImpl.addCustomers(customer);        }        return b;    }
复制代码

4.3 工具类代码(ReadExcel.java),即上述方法中readExcel.getExcelInfo(name ,file);语句所调用的方法以及其他相关的方法

Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。不过这首先得判断Excel的版本而选择不同的Workbook的方式(2003版本对应的是HSSFWorkbook,2007版本及以上对应的是XSSFWorkbook)。此外,一般来说先将在客户端用户上传的文件拷贝一份至服务器的本地磁盘中,然后再从这个拷贝文件中进行读取,这样就避免了因客户端的网络异常或其他状况而在读取时造成的数据流失或损坏的情况。

复制代码
package com.jun.util;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;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.apache.poi.xssf.usermodel.XSSFWorkbook;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.commons.CommonsMultipartFile;import com.jun.service.CustomerService;import com.jun.vo.Customer;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 filePath   * @return   */  public boolean validateExcel(String filePath){        if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){              errorMsg = "文件名不是excel格式";              return false;          }          return true;  }      /**   * 读EXCEL文件,获取客户信息集合   * @param fielName   * @return   */  public List<Customer> getExcelInfo(String fileName,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() + ".xlsx");        //将上传的文件写入新建的文件中       try {           cf.getFileItem().write(file1);        } catch (Exception e) {           e.printStackTrace();       }              //初始化客户信息的集合           List<Customer> customerList=new ArrayList<Customer>();       //初始化输入流       InputStream is = null;         try{          //验证文件名是否合格          if(!validateExcel(fileName)){              return null;          }          //根据文件名判断文件是2003版本还是2007版本          boolean isExcel2003 = true;           if(WDWUtil.isExcel2007(fileName)){              isExcel2003 = false;            }          //根据新建的文件实例化输入流          is = new FileInputStream(file1);          //根据excel里面的内容读取客户信息          customerList = getExcelInfo(is, isExcel2003);           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 is 输入流   * @param isExcel2003 excel是2003还是2007版本   * @return   * @throws IOException   */  public  List<Customer> getExcelInfo(InputStream is,boolean isExcel2003){       List<Customer> customerList=null;       try{           /** 根据版本选择创建Workbook的方式 */           Workbook wb = null;           //当excel是2003时           if(isExcel2003){               wb = new HSSFWorkbook(is);            }           else{//当excel是2007时               wb = new XSSFWorkbook(is);            }           //读取Excel里面客户的信息           customerList=readExcelValue(wb);       }       catch (IOException e)  {             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){            this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();       }              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){//第一列不读                   }else if(c==1){                       customer.setcName(cell.getStringCellValue());//客户名称                   }else if(c==2){                       customer.setSimpleName(cell.getStringCellValue());//客户简称                   }else if(c==3){                       customer.setTrade(cell.getStringCellValue());//行业                   }else if(c==4){                       customer.setSource(cell.getStringCellValue());//客户来源                   }else if(c==5){                       customer.setAddress(cell.getStringCellValue());//地址                   }else if(c==6){                       customer.setRemark(cell.getStringCellValue());//备注信息                   }               }           }           //添加客户           customerList.add(customer);       }       return customerList;  }}
复制代码

4.4 工具类代码(WDWUtil.java)

复制代码
public class WDWUtil {    // @描述:是否是2003的excel,返回true是2003     public static boolean isExcel2003(String filePath)  {           return filePath.matches("^.+\\.(?i)(xls)$");       }         //@描述:是否是2007的excel,返回true是2007     public static boolean isExcel2007(String filePath)  {           return filePath.matches("^.+\\.(?i)(xlsx)$");       }   }
复制代码

说明:上面的代码为了阅读便利而先贴的是父方法,后贴的是子方法,而在实际的代码编辑中一般是先编辑子方法,后编辑父方法,如上面应该是先编辑工具类的代码,再编辑服务层的代码,最后编辑控制器的代码。

 

运行结果:(先点击“选择文件”,再点击“导入Excel”)

数据库:

 

后记:此博客省略了模型层的代码,此项目采用的是Mybatis。

原创粉丝点击