java读取excel表格数据,通过Ajax方式上传文件

来源:互联网 发布:手抄报健康知识知多少 编辑:程序博客网 时间:2024/04/29 23:14

1.验证excel版本工具类

public class WDWUtil {    // @描述:是否是2003excel,返回true2003    public static boolean isExcel2003(String filePath)  {        return filePath.matches("^.+\\.(?i)(xls)$");    }    //@描述:是否是2007excel,返回true2007    public static boolean isExcel2007(String filePath)  {        return filePath.matches("^.+\\.(?i)(xlsx)$");    }}
2.对上传的文件进行数据处理,获取需要的数据

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 fileName     * @param Mfile     * @param request     * @return     */    private Workbook getExcelInfo(String fileName, MultipartFile Mfile, HttpServletRequest request) {        Workbook wb = null;        //spring文件上传的MultipartFile转换成CommonsMultipartFile类型        CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; 
<-------我的代码是读取excel数据,并不保存excel文件。若需要保存excel文件在读取数据,可阅读以下注释掉的代码 ------------------------      
    //String path = request.getSession().getServletContext().getRealPath("/");        //File file = new  File(path+"\\fileupload");        //创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)        // if (!file.exists()) file.mkdirs();        //新建一个文件        // File file1 = new File(path+"\\fileupload\\" + new Date().getTime() + ".xlsx");        //将上传的文件写入新建的文件中           /* try {                cf.getFileItem().write(file1);            } catch (Exception e) {                e.printStackTrace();            }*/
    //初始化输入流    InputStream is = null;    try {        //根据文件名判断文件是2003版本还是2007版本        boolean isExcel2003 = true;        if (WDWUtil.isExcel2007(fileName)) {            isExcel2003 = false;        }        //根据新建的文件实例化输入流        //is = new FileInputStream(file1);        is = cf.getInputStream();        //根据excel里面的内容读取客户信息        wb = getExcelInfo(is, isExcel2003, wb);        is.close();        //file1.delete();//清除此文件    } catch (Exception e) {        e.printStackTrace();    } finally {        if (is != null) {            try {                is.close();            } catch (IOException e) {                is = null;                e.printStackTrace();            }        }    }    return wb;}/** * 判断excel版本 * * @param is * @param isExcel2003 * @param wb * @return */private Workbook getExcelInfo(InputStream is, boolean isExcel2003, Workbook wb) {    //List<ComponentsCode> ComponentsCodeList = null;    try {        /** 根据版本选择创建Workbook的方式 */        //excel2003        if (isExcel2003) {            wb = new HSSFWorkbook(is);        } else {//excel2007            wb = new XSSFWorkbook(is);        }        //读取Excel里面客户的信息        // readExcelValue(wb);    } catch (IOException e) {        e.printStackTrace();    }    return wb;}
   
/** * 读取Excel里面的信息 * * @param fileName * @param Mfile * @param request * @return */public List<ComponentsCode> readExcelValue(String fileName, MultipartFile Mfile, HttpServletRequest request) {    Workbook wb = getExcelInfo(fileName, Mfile, request);    //得到第一个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<ComponentsCode> componentscodeList = new ArrayList<ComponentsCode>();    //循环Excel行数,从第二行开始。标题不入库    for (int r = 1; r < totalRows; r++) {        Row row = sheet.getRow(r);        if (row == null) continue;        ComponentsCode componentscode = new ComponentsCode();        //循环Excel的列        for (int c = 0; c < this.totalCells; c++) {            Cell cell = row.getCell(c);            if (cell != null) {                cell.setCellType(Cell.CELL_TYPE_STRING);                if (c == 0) {//第一列                    componentscode.setCodeId(cell.getStringCellValue());//零件识别码                }            }        }        //添加客户        if (StringUtils.isNotEmpty(componentscode.getCodeId())) { //当传入的excel并不符合我们的要求时,解析后的数据会是空            componentscodeList.add(componentscode);        }    }    return componentscodeList;}
}
3.业务层调用

controller

@PostMapping(value = "batchimport")@ResponseBodypublic AjaxResponse batchimport(@RequestParam(value = "filename") MultipartFile file, @RequestParam(value = "id") String id, HttpServletRequest request, HttpServletResponse response, AjaxResponse ar) throws IOException {    //获取文件名  String name = file.getOriginalFilename();    String Msg = importservice.batchImport(name, file, request, id);    ar.setMessage(Msg);    return ar;}



service


@DataSource("oracle")@Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)public String batchImport(String name, MultipartFile file, HttpServletRequest request, String id) {    //创建处理EXCEL    ReadExcel readExcel = new ReadExcel();    //验证文件名是否合格    if (!readExcel.validateExcel(name)) {        return "文件不是excel格式";    }    //解析excel,获取客户信息集合。    List<ComponentsCode> CodeList = readExcel.readExcelValue(name, file, request);    StringBuffer mes = new StringBuffer(" ");    if (CodeList.size() != 0) {        ComponentsCode code = new ComponentsCode();        code.setComponentsId(id);        List<ComponentsCode> list = componentscoderepository.select(code);//查找该零件的识别码        if (list.size() != 0) { // 该零件已有对应识别码,清除已有的            for (ComponentsCode data : list) {                componentscoderepository.deleteByPrimaryKey(data.getCodeId());            }        }        //迭代添加零件信息(注:实际上这里也可以直接将集合作为参数,在Mybatis的相应映射文件中使用foreach标签进行批量添加。)        Boolean isError = false;//未发生任何错误        int i = 1;        for (ComponentsCode componentscode : CodeList) {            List<ComponentsCode> result = componentscoderepository.select(componentscode);            if (result.size() == 0) {                componentscode.setComponentsId(id);                componentscode.setCreateTime(new Date());                componentscode.setUpdateTime(new Date());                componentscoderepository.insertCode(componentscode);            } else {                isError = true;                mes.append("" + i + "");            }        }        if (isError) {            mes.append("行识别码录入失败:原因:该行识别码已经被录入过");        }    } else {        mes.append("传入的excel数据为空");    }    return mes.toString();}

4.前台调用

传统的form表单提交会导致页面刷新,但是在有些情况下,我们不希望页面被刷新,这种时候我们都是使用Ajax的方式进行请求的。

如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件上传了。以下方法采用formdata对象

jsp页面

<form id="upload" >
<div class="form-group">
<input type="file" id="filename" name="filename">
</div>
</form>


js:

                function importExcel(){
                    var formData = new FormData();
                    formData.append("filename",$("#filename")[0].files[0]);
                    formData.append("componId",888);
                    $.ajax({
                        url :contextPath + "/import/batchimport",
                        type : 'POST',
                        data : formData,
// 告诉jQuery不要去处理发送的数据
                        processData : false,
// 告诉jQuery不要去设置Content-Type请求头
                        contentType : false,
                        beforeSend:function(){
                            console.log("正在进行,请稍候");
                        },
                        success : function(result) {
                            console.log(result)
                        },
                        error : function(responseStr) {
                            console.log("error");
                        }
                    });
                }




原创粉丝点击