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

java 使用EasyExcel导出Excel

程序员文章站 2024-03-20 14:00:22
...
maven仓库:
	   <dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>easyexcel</artifactId>
			<version>1.1.2-beta5</version></dependency>
   		 </dependencies>

后台代码:   
/**
	 * 导出Excel
	 */
	@RequestMapping("/exportMsg")
	@ResponseBody
	public int exportMsg(@RequestParam("codeId") Long codeId ,HttpServletResponse response) {
		int r = 0;
		try {

			List exportAuthUsers  = authenBusinessService.findByExportInviteCode(codeId);
			OutputStream out = response.getOutputStream();
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");
			String fileName= URLEncoder.encode("客户列表","utf-8");//设置导出格式
			response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
			ExcelUtil.writer(out,"人员列表",exportAuthUsers, ExportAuthUser.class);
			out.flush();
			r=1;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return r;
	}

后台工具类:

 /**
     * 导出Excel
     * @param out Servlet 流
     * @param sheetName sheet名称
     * @param data 数据
     * @param clazz 对应数据Class
     */
    public static void writer(OutputStream out, String sheetName, List<? extends BaseRowModel> data,Class<? extends BaseRowModel> clazz){
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        Sheet sheet1 = new Sheet(1, 0, clazz);
        sheet1.setSheetName(sheetName);
        sheet1.setAutoWidth(Boolean.TRUE);
        writer.write(data,sheet1);
        writer.finish();
    }


前台请求(不能使用ajax请求):
     $('#outExcel').click(function(){
            var  codeIds = $("#codeIds").val();
			window.location.href = '${ctx}/datas/exportMsg?codeId='+codeIds;
       }

 

转载于:https://my.oschina.net/u/3727427/blog/3055933