Java使用EasyExcel做导出功能

EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目 。在尽可能节约内存的情况下支持读写百M的Excel 。

Java使用EasyExcel做导出功能

官网首页

官方网站

https://easyexcel.opensource.alibaba.com/
废话不多说 直接开整:
先进行pom.xml要导入包进行添加:
com.alibabaeasyexcel2.2.10org.apache.poipoiorg.apache.poipoi-ooxmlpoi-ooxml-schemasorg.apache.poiorg.apache.poipoi4.1.2org.apache.poipoi-ooxml4.1.2org.apache.poipoi-ooxml-schemas4.1.2com.deepoovepoi-tl1.10.0
写个通用EasyExcel工具类:
import com.alibaba.excel.EasyExcel;import com.alibaba.excel.support.ExcelTypeEnum;import lombok.extern.slf4j.Slf4j;import javax.servlet.http.HttpServletResponse;import java.net.URLEncoder;import java.util.List;/** * EasyExcel工具类 */@Slf4jpublic class EasyExcelUtil {/*** 导出Excel(07版.xlsx)到web** @param response响应* @param excelName Excel名称* @param sheetName sheet页名称* @param clazzExcel要转换的类型* @param data要导出的数据* @throws Exception*/public static void export2Web(HttpServletResponse response, String excelName, String sheetName, Class clazz, List data) throws Exception {response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码excelName = URLEncoder.encode(excelName, "UTF-8");response.setHeader("Content-disposition", "attachment;filename="excelNameExcelTypeEnum.XLSX.getValue());EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);}}
返回参数:
import com.alibaba.excel.annotation.ExcelIgnore;import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.annotation.write.style.ColumnWidth;import io.swagger.annotations.ApiModelProperty;import lombok.Data;import java.io.Serializable;@Data@ApiModel(value = "https://www.itzhengshu.com/excel/VO", description = "导出列表Vo")public class VO implements Serializable {/*** 主键* @ExcelIgnore:导出列表不显示*/@ApiModelProperty(value = "https://www.itzhengshu.com/excel/主键")@ExcelIgnoreprivate Integer id;/*** 名称* @ColumnWidth(30):要显示导出的列表列:30代表列表宽度*/@ApiModelProperty(value = "https://www.itzhengshu.com/excel/名称")@ExcelProperty(value = "https://www.itzhengshu.com/excel/名称")@ColumnWidth(30)private String name;/*** 地址*/@ApiModelProperty(value = "https://www.itzhengshu.com/excel/地址")@ExcelProperty(value = "https://www.itzhengshu.com/excel/地址")@ColumnWidth(35)private String address;}
controller:
【Java使用EasyExcel做导出功能】/** * 导出数据列表 * * @return */@ApiOperation(value = "https://www.itzhengshu.com/excel/导出数据列表", notes = "导出数据列表")@GetMapping(value = "https://www.itzhengshu.com/expor")public void expor(@ApiIgnore Dto dto, HttpServletResponse response) {try {String fileName = "数据列表"DateUtils.getDate("yyyyMMddHHmmss");//Service调用相应查询数据方法List list = Service.expor(dto);EasyExcelUtil.export2Web(response, fileName, "数据列表", VO.class, list);} catch (Exception e) {logger.info("导出数据列表失败!失败信息:{}", e.getMessage());}}

相关经验推荐