SpringMVC/SpringBoot使用easypoi实现Excel文件导入导出功能实现




/**
 * @author Meixi   http://blog.csdn.net/liujianwd
 */
 首先讲导出功能
第一步:添加esaypoi依赖,在pom.xml中添加



org.jeecg
easypoi-base
2.3.1



org.jeecg
easypoi-web
2.3.1



org.jeecg
easypoi-annotation
2.3.1



第二步:编写实体类
/**
 * @author Meixi   http://blog.csdn.net/liujianwd
 */


@Entity
@ExcelTarget("sysStbId")
public class SysStbId {
/**
* stbId作为主键
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;


/**
* 机顶盒唯一标识
*/
@Excel(name = "用户账号", orderNum = "1", mergeVertical = true, isImportField = "iptvAccount")
private String iptvAccount;


/**
* 创建日期
*/
@Excel(name = "添加日期", orderNum = "2", mergeVertical = true, isImportField = "createDate")
@Temporal(TemporalType.TIMESTAMP)
@Column(columnDefinition="timestamp default CURRENT_TIMESTAMP")
private Date createDate;
}
/**
 * @author Meixi   http://blog.csdn.net/liujianwd
 */




上面代码没有添加set/get方法,通过给每个字段添加@Excel注解确定为导出文件的一列。
第三步编写Controler和Service
下面是Controller中的接口:
@RequestMapping(value = "/exprotStbIds")
    public Map download(HttpServletRequest request,HttpServletResponse response) throws IOException, BussinessException {
    fileService.download(request,response);
    return sucess();
        }




接下来是 Service的方法实现:
/**
 * @author Meixi   http://blog.csdn.net/liujianwd
 */
 
        @Override
public void download(HttpServletRequest request, HttpServletResponse response) throws BussinessException {
response.setHeader("content-Type", "application/vnd.ms-excel");
   // 下载文件的默认名称
   try {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("IptvAccountList","UTF-8") + ".xls");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   //编码
   response.setCharacterEncoding("UTF-8");
       Listlist=sysStbIdRepository.findAll();
   Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), SysStbId.class, list);
   try {
workbook.write(response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}






调用该接口后浏览器会自动下载该Excel表格,可以自行在浏览器选择存储的位置和名称。


接下来讲解Excel导入功能:
第一步同样是下载依赖:
/**
 * @author Meixi   http://blog.csdn.net/liujianwd
 */

org.apache.poi
poi
3.9


org.apache.poi
poi-ooxml
3.9



 
第二部编写Controller:
 
@RequestMapping(value = "/singleFile")
    public Map upload(@RequestParam("file") MultipartFile myfile,HttpServletRequest request,WebConfiguration webConfiguration) throws IOException, BussinessException {
    return fileService.upload(myfile, request, webConfiguration);
        }




第三部实现service方法:
/**
 * @author Meixi   http://blog.csdn.net/liujianwd
 */


@Override
public Map upload(MultipartFile myfile, HttpServletRequest request,WebConfiguration webConfiguration) throws BussinessException {
// TODO Auto-generated method stub
Mapresult=new HashMap();
    if (!myfile.isEmpty()) {
               System.out.println("文件名称: " + myfile.getName());
               System.out.println("文件原名: " + myfile.getOriginalFilename());
               // 如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
               String realPath = request.getSession().getServletContext().getRealPath(webConfiguration.getUploadPath());
               File file = new File(realPath, myfile.getOriginalFilename());
               try {
FileUtils.copyInputStreamToFile(myfile.getInputStream(), file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
               Setset=new HashSet();
               if(myfile.getOriginalFilename().toLowerCase().endsWith("xls")){                    
                try {
readXls(myfile.getInputStream(),set);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
               }else{
                   try {
readXlsx(file+"",set);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
               }
               result.put("code", 0);
        result.put("message", "上传成功");
        result.put("body", set);
           return result;        
        } 
    result.put("code", 1);
    result.put("message", "上传失败");
       return result;

}
private void readXlsx(String fileName,Setset) throws IOException {
   //这里的Set是我用来存储我需要使用的信息的,具体存什么可以根据具体需求来设置
 //String fileName = "D:\\excel\\xlsx_test.xlsx"; XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileName); // 循环工作表Sheet for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) { XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet); if (xssfSheet == null) { continue; } // 循环行Row for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) { XSSFRow xssfRow = xssfSheet.getRow(rowNum); if (xssfRow == null) { continue; } // 循环列Cell for (int cellNum = 0; cellNum <= xssfRow.getLastCellNum(); cellNum++) { XSSFCell xssfCell = xssfRow.getCell(cellNum); if (xssfCell == null) { continue; }
                    set.add(getValue(xssfCell));
                    System.out.print("   " + getValue(xssfCell));
                }
                System.out.println();
            }
        }
    }
      
/**
 * @author Meixi   http://blog.csdn.net/liujianwd
 */
 @SuppressWarnings("static-access") private String getValue(XSSFCell xssfCell) { if (xssfCell.getCellType() == xssfCell.CELL_TYPE_BOOLEAN) { return String.valueOf(xssfCell.getBooleanCellValue()); } else if (xssfCell.getCellType() == xssfCell.CELL_TYPE_NUMERIC) { return String.valueOf(xssfCell.getNumericCellValue()); } else { return String.valueOf(xssfCell.getStringCellValue()); } }
/**
 * @author Meixi   http://blog.csdn.net/liujianwd




 */




至此我得到的我想要的 信息存在了Setset中,并通过result传回。



















你可能感兴趣的:(SpringMVC,SpringBoot)