详细webMVC实现提交excel后台并读取数据

使用MVC上传EXCEL表格,主要是用到MultipartFile类进行文件的获取,然后把文件读取成EXCEL对象再进行处理,Java有处理Excel对象的包,需要导入才能使用,具体的步骤,下面的用的MatchInfo是一个实体类,可以不用管

转载自 南国樱花祭的文章 这是我看的文章,基本复制他的代码,如果要看配置上传文件的大小限制的可以点进去看看

maven项目的要先添加pom依赖,不是maven的也要添加jar包,可以自行上网下载

<!-- 处理excel表格需要的jar包 三个 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.10-FINAL</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.10-FINAL</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-FINAL</version>
        </dependency>


1.先前端写form表单

enctype="multipart/form-data" 是提交文件时必须要加的属性,不然后台的Controller是获取不到这个文件

accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"是规定只能选取excel文件

<form action="submitExcel" method="post" enctype="multipart/form-data">
                        <table>
                            <tr>
                                <td>根据excel表格录入 :</td>
                                <td><input type="file" id="file" name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"></td>
                                <td><input type="submit" value="批量录入"></td>
                            </tr>
                        </table>
                    </form>

2.Controller获取请求

参数中可以写很多种写法我是直接写MultipartFile file,这样要求就是你前端页面的文件组件 name要是file

也可以@RequestParam(value="file") MultipartFile fileXXXX   要求是红色的file是前端的name

@RequestMapping(value = "submitExcel",method = RequestMethod.POST)
    public void MatchExcel(HttpServletRequest request, HttpServletResponse response,MultipartFile file) throws IOException {
        //判断文件是否为空
        if(file==null) {return;}
        //获取文件名
        String name=file.getOriginalFilename();
        //进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)
        long size=file.getSize();
        if(name==null || ("").equals(name) && size==0) {return;}

        //获取项目web路径,主要是临时写一个文件在webapp目录下
        String pic_path = request.getServletContext().getRealPath("/");
        //批量导入。参数:文件名,文件。
        int b = submitService.insertMatchesFromExcel(name,file,pic_path+"static"+"/excel");
        
if(b==0){
            String Msg ="批量导入EXCEL成功!";request.getSession().setAttribute("msg",Msg);
        }else{
            String Msg ="批量导入EXCEL失败!";
            request.getSession().setAttribute("msg",Msg);
        }
        return;

        }

3.service服务层处理数据

创建一个下面的要写的工具类,然后读取文件

public int insertMatchesFromExcel(String fileName, MultipartFile mfile, String systemPage) {        ReadExcel readExcel=new ReadExcel();//初始化一个EXCEL读取对象
        List<MatchInfo> Mlist=null;
        Mlist=readExcel.getExcelInfo(fileName,mfile,systemPage);//读取
        for (MatchInfo m:Mlist){
            System.out.println(m.getId());
        }
        return 0;
    }

4.工具类验证文件和进行数据的遍历,解析,读取等

4.1WDWutil类,函数是使用正则表达式判断文件是xls还是xlsx文件

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)$");
    }
}
4.2READEXCEL工具类,真正处理信息的类

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
     * @return
     */
    public List<MatchInfo> getExcelInfo(String fileName, MultipartFile Mfile,String systemPage){

        //把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
        CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; //获取本地存储路径
        File file = new  File(systemPage);//此文件为存放的目录
        //创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)
        if (!file.exists()) {file.mkdirs();}//存在则不会创建
        //新建一个文件
        File file1 = new File(systemPage + "/"+new Date().getTime() + ".xlsx");
        //将上传的文件写入新建的文件中
        try {
            cf.getFileItem().write(file1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //初始化赛程信息的集合
        List<MatchInfo> customerList=new ArrayList<MatchInfo>();
        //初始化输入流
        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<MatchInfo> getExcelInfo(InputStream is,boolean isExcel2003){
        List<MatchInfo> 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<MatchInfo> readExcelValue(Workbook wb){
        //得到第一个shell,只读取第一个sheet,多个sheet可以循环
        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<MatchInfo> customerList=new ArrayList<MatchInfo>();
        MatchInfo matchInfo;
        //循环Excel行数,从第二行开始。标题不入库
        for(int r=1;r<totalRows;r++){
            Row row = sheet.getRow(r);
            if (row == null) {continue;}//为空跳过
            matchInfo = new MatchInfo();

            //循环Excel的列
            for(int c = 0; c <this.totalCells; c++){
                Cell cell = row.getCell(c);
                if (null != cell){
                    cell.setCellType(Cell.CELL_TYPE_STRING);//设置从EXCEL获取的数据类型为String,否则容易读取的时候要根据内容
                    进行getString类型的数据还是整数类型的判断,容易报错,这样写就可以后面获取的数据都获取成String再转成其他类型就可以了
                    if(c==0){//第一列数据
                        matchInfo.setId(Long.valueOf(cell.getStringCellValue()));//获取数据数值并由String转成Long
                    }else if(c==1){//第二列数据
                        matchInfo.setSeason(cell.getStringCellValue());//获取数据数值并赋值给MatchInfo的season属性
                    }
                }
            }
            //添加该对象到对象集合中去
            customerList.add(matchInfo);
        }
        return customerList;
    }
}
        }

对EXCEL的读取基本就完成了,大概就是上传的文件转成File对象,然后用java已经有的EXCEL对象进行处理数据,除去验证文件类型等环节,基本就是file文件读取成excel对象,然后获取行,列,读值

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值