欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何使用POI导入导出到excel表格

程序员文章站 2024-02-24 12:57:58
...

如何使用POI导入导出到excel表格

鉴于本人水平如发现不足之处希望大家指出

导入


@RequestMapping("user/uploadExcel")
    @ResponseBody 
    public ResultMessage uploadExcel(HttpServletRequest request) throws IOException, InvalidFormatException{
        /*
        System.out.println("byubjk");
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        *///把所有得到的文件所对应的表的数据放入一个map中
        System.out.println("--------------------导入excel");
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
       Map<String, MultipartFile> map =      multipartHttpServletRequest.getFileMap();

       int i=0;
         for (String  key : map.keySet()) {
               MultipartFile file = map.get(key);//得到当个文件
               //得到文件相关的输入流
               InputStream is = file.getInputStream();

               //根据上传的excel文件  构建一个WorkBook对象
               Workbook workbook = WorkbookFactory.create(is);
               Sheet wsheet =  workbook.getSheetAt(0);//读取第一个sheet表格
               String fieldsStr = "userChName,mobilePhone,email,userSex,userName,orgName,provinceName,cityName";

               ExcelUtil excelUtil = new ExcelUtil();
               List<Map<String, Object>> list =   excelUtil.readSimple(wsheet, 2, fieldsStr.split(","));
               //处理性别

              for (Map<String, Object> map2 : list) {
                Object sex = map2.get("userSex");
                if (sex!=null&&!sex.equals("")) {
                     if ("男".equals(sex)) {
                        sex = 1;
                    }else if ("女".equals(sex)) {
                        sex = 2;
                    }else if ("保密".equals(sex)) {
                        sex = 3;
                    }
                }else{
                    sex = null;
                }

                map2.put("userSex", sex);
                //处理部门
                Object orgName = map2.get("orgName");
                //根据部门名称查询部门id
                long orgId = orgService.selectOrgIdByOrgName(orgName+"");

                map2.put("orgId", orgId);
                System.out.println(map2);
              }

             System.out.println("插入的list:-------------------------"+list);
               i  =   userService.insertDoubleUser(list);
           }
           ResultMessage message = new ResultMessage();
             if (i>0) {
                message.setSuccess(true);
            }else{
                message.setSuccess(false);
            }

            return message; 
    }

导出


@RequestMapping("/user/exportUser")
        @ResponseBody
        public ResultMessage  exportExcel(HttpServletRequest request,HttpServletResponse response) throws Exception{
            System.out.println("--------------------导出excel");
            Map<String, Object> paramMap = super.getParam(request);
            ExcelUtil excelUtil = new ExcelUtil();
            //HSSFWorkBook对象
            //创建HSSFWorkBook对象
            HSSFWorkbook wwb = new HSSFWorkbook();
            //创建sheet对象
            HSSFSheet wsheet = wwb.createSheet();
            //excel导出的工具类
            SimpleExportParameter parameters = new SimpleExportParameter();
            String fieldsIdStr = "userChName,orgName,userSex,mobilePhone,provinceName,cityName,contryName,userBirthday";
            // 导出的excel文件中显示的名称,跟fieldsIdStr顺序一致,个数相等
            String fieldsNameStr = "姓名,所属组织,性别,电话,省份,地市,区县,生日";
            // 导出的excel文件的列宽,以上面的fieldsIdStr,fieldsNameStr个数相等
            String widthsStr = "10,30,20,20,20,20,20,20";

            List<Map<String, Object>> list = userService.exportAllUser(paramMap);
            //特殊字段
            //性别
            for (Map<String, Object> map : list) {
                Object sex = map.get("userSex");
                //sex = null+""===> "null"
                if (sex!=null&&!sex.equals("")) {
                    int userSex = Integer.parseInt(sex+"");
                    if (userSex==1) {
                        sex = "男";
                    }else if (userSex==2) {
                        sex = "女";
                    }else {
                        sex = "保密";
                    }
                }else{
                    sex = "未知";
                }
                map.put("userSex", sex);
            }

            parameters.setDataList(list);
            parameters.setFieldsName(fieldsNameStr.split(","));
            parameters.setFieldsId(fieldsIdStr.split(","));
            parameters.setSheetName("公司员工信息");
            parameters.setTitle("公司员工信息");
            parameters.setWidths(widthsStr.split(","));
            excelUtil.simpleExport(wwb, wsheet, parameters);


            OutputStream fileOutputStream= response.getOutputStream();

            String time = CalendarHelper.getDateTime();
            String fileName = "公司员工信息-"+time+".xls";
            //设置响应头
           response.setHeader("Content-disposition", "attachment; filename="+new String(fileName.getBytes("utf-8"),"iso-8859-1")); 
           response.setContentType("application/msexcel");
           wwb.write(fileOutputStream);

            fileOutputStream.flush();
            fileOutputStream.close();

            ResultMessage message = new ResultMessage();
            message.setMessage("导出成功");
            message.setSuccess(true);
            return message;
        }


JS代码

function exportExcel(){
    location.href="user/exportUser";
}
function importExcel(){
    //弹框  form
    //文件上传
    //1,form  enctype="multipart/form-data"
    //2,method 为post
    //3,提供一个 type为file的input
    var htmlStr = "";
        htmlStr += '<div style="width:600px;background-color:cfcccc" >';    
        htmlStr += '<div style="display:block; padding-bottom:20px;" align="center" >';
        htmlStr += '<form  id = "userExcelFileFormId"  action="user/uploadExcel" enctype="multipart/form-data" method="post" >';
        htmlStr += '<input type="file" id="userExcelFile" name="userExcelFile" onchange="ValidateFileType()" >';
        htmlStr += ' <input type="submit"  value="导入"  />  ';
        htmlStr += '</form>';
        htmlStr += '</table>';
        htmlStr += '</div>';
        htmlStr += '</div>';
        layer.open({
              type: 1,
              skin: 'layui-layer-rim', //加上边框 这个属性可以去static/layer/skin/default/layer.css找到合适的样式 取的是“.”这个属性的前后值
              area: ['auto', 'auto'], //宽高 
              content: htmlStr
            });

    SubmitFuc();    
}

/**
 * 验证上传的文件是否是excel格式的
 * @returns
 */
function ValidateFileType(){
    var fileName = $("#userExcelFile").val();
    var suffix = fileName.substring(fileName.lastIndexOf(".")+1);
    console.log(suffix);
    if (suffix!="xls" && suffix!="xlsx") {
        alert("请选择excel格式的文件");
        $("#userExcelFile").val("");
        return;
    }

}

function SubmitFuc() {
    var options = {
        beforeSubmit : ShowRequest, // 提交前处理
        success : ShowResponse, // 处理完成
        resetForm : true,
        dataType : 'json'
    };

    $('#userExcelFileFormId').submit(function() {//提交表单执行的方法

        var file = document.getElementById("userExcelFile");
        if(!file.value){
            alert("请选Excel文档!");
            return false;
        }

    $(this).ajaxSubmit(options);//用ajax提交表单
    return false;
});
}

function  ShowRequest(){}
function ShowResponse(){
    alert("导入成功");
    //location.href="user/userMana";
    layer.closeAll();

    location.reload();
}