java 导入导出

导出controller:
@RequestMapping( value = “/excelOut”)
public void excelStandardTemplateOut(HttpServletRequest request,
HttpServletResponse response) throws IOException{
String str = request.getSession().getServletContext().getRealPath(“/”);
str = str +”/WEB-INF/classes/附件2.攀枝花市统一社会信用代码转码率情况表.xlsx”;//Excel模板所在的路径。
File f = new File(str);
// 设置response参数,可以打开下载页面
response.reset();
response.setContentType(“application/vnd.ms-excel;charset=utf-8”);
try {
response.setHeader(“Content-Disposition”, “attachment;filename=”+ new String((“代码转换统计表模板” + “.xlsx”).getBytes(), “iso-8859-1”));//下载文件的名称
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(f));
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}

导入controller:
@RequestMapping(“/importFile”)
public @ResponseBody ModelMap importFile(HttpServletRequest request, HttpServletResponse response)throws IllegalStateException, IOException {
ModelMap model=new ModelMap();

    String url=request.getParameter("fileurl");
    String fileType = url.substring(url.lastIndexOf(".") + 1, url.length());

    String str = request.getSession().getServletContext().getRealPath("/");  
    str = str +"/WEB-INF/classes/"+url.substring(url.lastIndexOf("/"));//Excel模板所在的路径。

// File f = new File(str);
model.addAttribute(“result”, “导入成功”);

    URL urlfile = null;
    HttpURLConnection httpUrl = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try
    {
        urlfile = new URL(url);
        httpUrl = (HttpURLConnection)urlfile.openConnection();
        httpUrl.connect();
        bis = new BufferedInputStream(httpUrl.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream(str));
        int len = 2048;
        byte[] b = new byte[len];
        while ((len = bis.read(b)) != -1)
        {
            bos.write(b, 0, len);
        }
        System.out.println("上传成功");
        bos.flush();
        bis.close();
        httpUrl.disconnect();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            bis.close();
            bos.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    InputStream stream = new FileInputStream(str);

    Workbook wb = null;
    if (fileType.equals("xls")) {
        wb = new HSSFWorkbook(stream);
    } else if (fileType.equals("xlsx")) {
        wb = new XSSFWorkbook(stream);
    } else {
        model.addAttribute("result", "您输入的excel格式不正确");
        return model;
    }
    //行政许可
    Sheet sheet1 = wb.getSheetAt(0);
    // 得到Excel的行数
     int totalRows = sheet1.getPhysicalNumberOfRows();
     String sheetname = sheet1.getSheetName();
     if(!"代码转换统计表".equals(sheetname)){
         model.addAttribute("result", "您输入的excel格式不正确");
        return model;
     }
     int totalCells = 0;
     // 得到Excel的列数(前提是有行数)
     if (totalRows > 1 && sheet1.getRow(0) != null) {
         totalCells = sheet1.getRow(0).getPhysicalNumberOfCells();
     }


     CreditCodeConversion al = null;
     MyResult<Object> result = null;
     try {
         //行政许可
         if(sheet1.getLastRowNum() == 0 && sheet1.getPhysicalNumberOfRows() == 0 ){
                model.addAttribute("result", "您的excel格式为空");
                return model;
         }else{
            for (int r = 3; r < totalRows; r++) {
                 Row row = sheet1.getRow(r);    

                 if(row.getCell(4) == null || String.valueOf(row.getCell(4)).equals("")){
                     return model;
                 }

                 al = new CreditCodeConversion();
                 al.setRegistrationDepartment(String.valueOf(row.getCell(0) == null?"":row.getCell(0)));


                 /*Date date = row.getCell(1).getDateCellValue();
                 DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");*/
                 /*if(date != null){
                     Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(formater.format(date)));
                     al.setRegistrationTime(date2);
                 }else{
                     Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse("0000-00-00");
                     al.setRegistrationTime(date2);
                 }*/
                 row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                 al.setRegistrationTime(row.getCell(1).getStringCellValue() == null?"":row.getCell(1).getStringCellValue());
                 al.setOrganizationName(String.valueOf(row.getCell(2) == null?"":row.getCell(2)));

                 al.setInstitutionalNature(String.valueOf(row.getCell(3) == null?"":row.getCell(3)));

                 row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                 al.setUnifiedSocialCreditCode(row.getCell(4).getStringCellValue() == null?"":row.getCell(4).getStringCellValue());

                 row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                 al.setIstrationMark(row.getCell(5).getStringCellValue() == null?"":row.getCell(5).getStringCellValue());

                 al.setLegalRepresentative(String.valueOf(row.getCell(6) == null?"":row.getCell(6)));

                 al.setBusinessLocation(String.valueOf(row.getCell(7) == null?"":row.getCell(7)));
                 al.setState("2");
                 creditCodeConversionService.addRecord(request, response, al);
             }
        }
    } catch (Exception e) {
        model.addAttribute("result", e.getMessage());
    }finally{
        return model;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28710139/article/details/81776479