StringBoot数据导入Excel

//Excel文本导入到本地数据库 具体看下面代码

public class Response implements Serializable {//工具类
    private boolean success = true;
    private Object result = null;
    private String error = "";
}

public Response importExcel(HttpServletRequest request, @RequestParam("excelFile") MultipartFile excelFile) throws Exception {
    Response response = new Response();
    BaseUser baseUser = (BaseUser) request.getSession().getAttribute("user");
    List<List<List<String>>> data = ExcelUtil.readXlsxNotBlank(excelFile);
    Map<String, String> params = null;
    List<Map<String, String>> lists = new ArrayList<Map<String, String>>();
    String jsonString = null;

    Integer customer_cclstore_index = null;//店号
    String customer_ccl_store_code = null;

    Integer customer_ccl_store_index_name = null;//门店名称
    String customer_ccl_store_name = null;

    Integer customer_ccl_merchant_index_name = null;//商户名称
    String customer_ccl_merchant_name = null;

    Integer customer_ccl_store_index_province_name = null;//省
    String customer_ccl_store_province_name= null;

    Integer customer_ccl_store_index_city_name = null;//市
    String customer_ccl_store_city_name = null;

    Integer customer_ccl_store_index_address = null;//地址
    String customer_ccl_store_address = null;

    Integer customer_ccl_store_index_contacts = null;//联系人
    String customer_ccl_store_contacts = null;

    Integer customer_ccl_store_index_mobile = null;//联系电话
    String customer_ccl_store_mobile = null;

    Integer customer_ccl_store_index_email = null;//邮箱
    String customer_ccl_store_email = null;
    int count = 0;
    try{
        for (List<List<String>> result : data) {
            if (result.size() < 1) {
                continue;
            }
            for (int i = 0; i < result.size(); i++) {
                List<String> list = result.get(i);
                if (i == 0 || i==1 ) {
                    for (int j = 0; j < list.size(); j++) {
                        if (list.get(j) != null && "店号".equals(list.get(j).toString())) {
                            customer_cclstore_index = j;
                        } else if (list.get(j) != null && "门店名称".equals(list.get(j).toString())) {
                            customer_ccl_store_index_name = j;
                        } else if (list.get(j) != null && "商户".equals(list.get(j).toString())) {
                            customer_ccl_merchant_index_name = j;
                        } else if (list.get(j) != null && "省".equals(list.get(j).toString())) {
                            customer_ccl_store_index_province_name = j;
                        } else if (list.get(j) != null && "市".equals(list.get(j).toString())) {
                            customer_ccl_store_index_city_name = j;
                        } else if (list.get(j) != null && "地址".equals(list.get(j).toString())) {
                            customer_ccl_store_index_address = j;
                        }else if (list.get(j) != null && "联系人".equals(list.get(j).toString())) {
                            customer_ccl_store_index_contacts = j;
                        }else if (list.get(j) != null && "联系电话".equals(list.get(j).toString())) {
customer_ccl_store_index_mobile = j;
}else if (list.get(j) != null && "邮箱".equals(list.get(j).toString())) {
customer_ccl_store_index_email = j;
}
                    }
                } else {
params = new HashMap<String, String>();
customer_ccl_store_code = list.get(customer_cclstore_index) == null ? "" : list.get(customer_cclstore_index).toString();
customer_ccl_store_name = list.get(customer_ccl_store_index_name) == null ? "" : list.get(customer_ccl_store_index_name).toString();
customer_ccl_merchant_name = list.get(customer_ccl_merchant_index_name) == null ? "" : list.get(customer_ccl_merchant_index_name).toString();
customer_ccl_store_province_name = list.get(customer_ccl_store_index_province_name) == null ? "" : list.get(customer_ccl_store_index_province_name).toString();
customer_ccl_store_city_name = list.get(customer_ccl_store_index_city_name) == null ? "" : list.get(customer_ccl_store_index_city_name).toString();
customer_ccl_store_address = list.get(customer_ccl_store_index_address) == null ? "" : list.get(customer_ccl_store_index_address).toString();
customer_ccl_store_contacts = list.get(customer_ccl_store_index_contacts) == null ? "" : list.get(customer_ccl_store_index_contacts).toString();
customer_ccl_store_mobile = list.get(customer_ccl_store_index_mobile) == null ? "" : list.get(customer_ccl_store_index_mobile).toString();
customer_ccl_store_email = list.get(customer_ccl_store_index_email) == null ? "" : list.get(customer_ccl_store_index_email).toString();
params.put("customer_ccl_store_code", customer_ccl_store_code);
params.put("customer_ccl_store_name", customer_ccl_store_name);
params.put("customer_ccl_merchant_name", customer_ccl_merchant_name);
params.put("customer_ccl_store_province_name", customer_ccl_store_province_name);
params.put("customer_ccl_store_city_name", customer_ccl_store_city_name);
params.put("customer_ccl_store_address", customer_ccl_store_address);
params.put("customer_ccl_store_contacts", customer_ccl_store_contacts);
params.put("customer_ccl_store_mobile", customer_ccl_store_mobile);
params.put("customer_ccl_store_email", customer_ccl_store_email);
lists.add(params);//循环找到每一个值放到list集合

}
            }
        }
    }catch (Exception e){
e.getMessage ();
response.setError ( "文件格式错误!请重新选择!" );
response.setSuccess ( false );
return  response;
}
jsonString = JSONArray.fromObject(lists).toString();

List<Map<String, String>> lists = JSONArray.fromObject(jsonString);
    //具体业务代码存到数据库
}

//工具类

ExcelUtil.readXlsxNotBlank

   public static  List<List<List<String>>> readXlsxNotBlank(MultipartFile excelFile) throws IOException {
        String originFileName = excelFile.getOriginalFilename();
        if(!originFileName.endsWith(".xlsx") || StringUtils.isEmpty(originFileName)){
            throw new NullPointerException("文件格式错误");
        }
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(excelFile.getInputStream());
        List<List<List<String>>>  data = new ArrayList<>();
        //循环每一页,并处理当前页
        for(XSSFSheet xssfSheet : xssfWorkbook) {
            if(xssfSheet == null) {
                continue;
            }
            List<List<String>> result = new ArrayList<List<String>>();
            //处理当前页,循环读取每一行
            for(int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                if (StringUtils.isEmpty(xssfRow)) {
                    continue;
                }
                int minColIx = xssfRow.getFirstCellNum();
                int maxColIx = xssfRow.getLastCellNum();
                List<String> rowList = new ArrayList<String>();
                // 遍历这行,获取处理每个cell元素
                int ia=minColIx;
                for(int colIx = minColIx; colIx < maxColIx; colIx++) {
                    XSSFCell cell = xssfRow.getCell(colIx);
                    if(cell != null){
                        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                    }
                    if (cell == null||cell.toString()==null||cell.toString().trim().length()==0)
                        ia++;
                    rowList.add(cell == null?null:cell.toString());
                }
                if(ia!=maxColIx)
                    result.add(rowList);
            }
            data.add(result);
        }
        return data;
    }

//========================================================================================================导出

public  Response  exportList(HttpServletRequest request , HttpServletResponse responses ,String merchant_id){
        Response response = new Response();
        response = crmStore.exportList(merchant_id); //首先根据自己得需求查询出需要的数据(查询数据)
        ExportCrmDaos ex = new ExportCrmDaos();//工具类
        if(response.getResult () != null){
            //导出方法
           ex.exportExcel ( responses, (List<Map<String, Object>>) response.getResult() );
        }else{
            Response errResponse = new Response();
            errResponse.setSuccess(false);
            errResponse.setError("查询失败");
            responses.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try{
                out = responses.getWriter();
                out.println( JSONObject.fromObject(errResponse).toString());
            }catch(Exception e){
                log.error(e.getMessage());
            }finally {
                if(out!=null){
                    out.close();
                }
            }
        }
        return  response;
    }

 public Response exportList(String merchant_id){
        Response response = new Response ();
        List<Map<String,Object>> fault_list = new ArrayList<Map<String,Object>>();
        StringBuffer sql = new StringBuffer();
        List<Object> params_fault = new ArrayList<Object>();

        List<Map<String,Object>> findeListByName = jdbcTemplate.queryForList ( " select id,name as nameMerchant from customer_ccl_merchant where id= ?" ,new Object[]{merchant_id} );
        sql.append ( "select s.*,m.name as merchant_name from customer_ccl_store s join customer_ccl_merchant m on s.merchant_id = m.id where 1=1 \n" );
        if(merchant_id != null && !merchant_id.equals ( "" ) ){
            sql.append(" and m.name = ? ");
            params_fault.add(findeListByName.get ( 0 ).get ( "nameMerchant" ));
            System.err.println ( "####################################"+findeListByName.get ( 0 ).get ( "nameMerchant" ) );
            fault_list = jdbcTemplate.queryForList(sql.toString(),params_fault.toArray());
        }else{
            fault_list = jdbcTemplate.queryForList(sql.toString());

        }
        response.setResult(fault_list);
        return  response;
    }

//工具类

public class ExportCrmDaos {

    Logger log = Logger.getLogger(this.getClass());

  /*  Integer no_index_ = 0;
    String no_title_ = "序号";*/

    Integer no_index = 0;
    String no_title = "店号"; //store_code

    Integer fault_no_index = 1;
    String fault_no_title = "门店名称";//store_name

    Integer merchant_index = 2;
    String merchant_title = "商户"; //merchant_name

    Integer store_index = 3;
    String store_title = "省";//province_name

    Integer province_index = 4;
    String province_title = "市";//city_name

    Integer city_index = 5;
    String city_title = "地址";//address

    Integer address_index = 6;
    String address_title = "联系人";//contacts

    Integer fault_describe_index = 7;
    String fault_describe_title = "联系电话";//mobile

    Integer model_index = 8;
    String model_title = "邮箱";//email

    public void exportExcel(HttpServletResponse httpResponse, List<Map<String,Object>> fault_list) {
       // System.err.println ( "共"+fault_list+"数据" );
        //设置下载信息
        String file_name = DateUtil.format(new Date ())+".xlsx";
        httpResponse.setContentType("application/force-download");
        httpResponse.addHeader("Content-Disposition", "attachment;fileName=" + file_name);
        //创建下载对象
        try{
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet();
            //创建标题 合并单元格
            CellRangeAddress titleRegion = new CellRangeAddress(0, 0, 0, 9);
            sheet.addMergedRegion(titleRegion);
            Row titleRow = sheet.createRow(0);
            titleRow.createCell(0).setCellValue("门店记录");
            //创建表头
            Row lableRow = sheet.createRow(1);
           // lableRow.createCell(no_index_).setCellValue(no_title_);
            lableRow.createCell(no_index).setCellValue(no_title);
            lableRow.createCell(fault_no_index).setCellValue(fault_no_title);
            lableRow.createCell(merchant_index).setCellValue(merchant_title);
            lableRow.createCell(store_index).setCellValue(store_title);
            lableRow.createCell(province_index).setCellValue(province_title);
            lableRow.createCell(city_index).setCellValue(city_title);
            lableRow.createCell(address_index).setCellValue(address_title);
            lableRow.createCell(fault_describe_index).setCellValue(fault_describe_title);
            lableRow.createCell(model_index).setCellValue(model_title);
            //填写内容
            int now_row_index = 2;
            //int row_no = 1;
            for(Map<String,Object> fault_info : fault_list){
                Row dataRow = sheet.createRow(now_row_index);
              //  dataRow.createCell(no_index_).setCellValue(row_no);merchant_name
                dataRow.createCell(no_index).setCellValue( ObjectUtils.isEmpty(fault_info.get("code"))?"":fault_info.get("code").toString());
                dataRow.createCell(fault_no_index).setCellValue( ObjectUtils.isEmpty(fault_info.get("name"))?"":fault_info.get("name").toString());
                dataRow.createCell(merchant_index).setCellValue(ObjectUtils.isEmpty(fault_info.get("merchant_name"))?"":fault_info.get("merchant_name").toString());
                dataRow.createCell(store_index).setCellValue(ObjectUtils.isEmpty(fault_info.get("province_name"))?"":fault_info.get("province_name").toString());
                dataRow.createCell(province_index).setCellValue(ObjectUtils.isEmpty(fault_info.get("city_name"))?"":fault_info.get("city_name").toString());
                dataRow.createCell(city_index).setCellValue(ObjectUtils.isEmpty(fault_info.get("address"))?"":fault_info.get("address").toString());
                dataRow.createCell(address_index).setCellValue(ObjectUtils.isEmpty(fault_info.get("contacts"))?"":fault_info.get("contacts").toString());
                dataRow.createCell(fault_describe_index).setCellValue(ObjectUtils.isEmpty(fault_info.get("mobile"))?"":fault_info.get("mobile").toString());
                dataRow.createCell(model_index).setCellValue(ObjectUtils.isEmpty(fault_info.get("email"))?"":fault_info.get("email").toString());
                now_row_index+=1;
                //row_no++;
            }
            httpResponse.setContentType("application/octet-stream;charset=UTF-8");
            httpResponse.setHeader("Content-Disposition", "attachment;filename="+ System.currentTimeMillis()+".xlsx");
            httpResponse.addHeader("Pargam", "no-cache");
            httpResponse.addHeader("Cache-Control", "no-cache");
            //输出
            OutputStream outputStream = httpResponse.getOutputStream();
            workbook.write(outputStream);
        }catch (Exception e1){
            e1.printStackTrace();
            Response errResponse = new Response();
            errResponse.setSuccess(false);
            errResponse.setError("查询失败");
            httpResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try{
                out = httpResponse.getWriter();
                out.println( JSONObject.fromObject(errResponse).toString());
            }catch(Exception e2){
                log.error(e2.getMessage());
            }finally {
                if(out!=null){
                    out.close();
                }
            }
        }
    }
}

转载于:https://www.cnblogs.com/ysySelf/p/11024133.html

猜你喜欢

转载自blog.csdn.net/weixin_33806914/article/details/93183334
今日推荐