- 使用easyexcel导出excel
- easyexcel简介
- 使用easyexcel
- 1.导入依赖
- 2.工具类
- ①FileUtils:作为文件处理
- ②字符串工具类StringUtils
- ③数据转换类(防止数据过大失真)ExcelBigNumberConvert
- 3.ExcelUtils
- 4.创建(修改)导出对象模板类
- 测试
- 使用easyexcel导入excel
使用easyexcel导出excel easyexcel简介
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便
使用easyexcel 1.导入依赖2.工具类 ①FileUtils:作为文件处理//easyexcel主要依赖 cn.hutool hutool-all 5.7.14 com.alibaba easyexcel 3.0.5 org.projectlombok lombok true
import cn.hutool.core.io.FileUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FileUtils extends FileUtil {
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
response.setHeader("Content-disposition", contentDispositionValue.toString());
response.setHeader("download-filename", percentEncodedFileName);
}
public static String percentEncode(String s) throws UnsupportedEncodingException {
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\+", "%20");
}
}
②字符串工具类StringUtils
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.AntPathMatcher;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StringUtils extends org.apache.commons.lang3.StringUtils {
public static String blankToDefault(String str, String defaultValue) {
return StrUtil.blankToDefault(str, defaultValue);
}
public static boolean isEmpty(String str) {
return StrUtil.isEmpty(str);
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
public static String trim(String str) {
return StrUtil.trim(str);
}
public static String substring(final String str, int start) {
return substring(str, start, str.length());
}
public static String substring(final String str, int start, int end) {
return StrUtil.sub(str, start, end);
}
public static String format(String template, Object... params) {
return StrUtil.format(template, params);
}
public static boolean ishttp(String link) {
return Validator.isUrl(link);
}
public static Set str2Set(String str, String sep) {
return new HashSet<>(str2List(str, sep, true, false));
}
public static List str2List(String str, String sep, boolean filterBlank, boolean trim) {
List list = new ArrayList<>();
if (isEmpty(str)) {
return list;
}
// 过滤空白字符串
if (filterBlank && isBlank(str)) {
return list;
}
String[] split = str.split(sep);
for (String string : split) {
if (filterBlank && isBlank(string)) {
continue;
}
if (trim) {
string = trim(string);
}
list.add(string);
}
return list;
}
public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {
return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences);
}
public static String toUnderScoreCase(String str) {
return StrUtil.toUnderlineCase(str);
}
public static boolean inStringIgnoreCase(String str, String... strs) {
return StrUtil.equalsAnyIgnoreCase(str, strs);
}
public static String convertToCamelCase(String name) {
return StrUtil.upperFirst(StrUtil.toCamelCase(name));
}
public static String toCamelCase(String s) {
return StrUtil.toCamelCase(s);
}
public static boolean matches(String str, List strs) {
if (isEmpty(str) || CollUtil.isEmpty(strs)) {
return false;
}
for (String pattern : strs) {
if (isMatch(pattern, str)) {
return true;
}
}
return false;
}
public static boolean isMatch(String pattern, String url) {
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url);
}
@SuppressWarnings("unchecked")
public static T cast(Object obj) {
return (T) obj;
}
}
③数据转换类(防止数据过大失真)ExcelBigNumberConvert
import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ObjectUtil; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; import lombok.extern.slf4j.Slf4j; import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.metadata.data.WriteCellData; import java.math.BigDecimal; @Slf4j public class ExcelBigNumberConvert implements Converter3.ExcelUtils{ @Override public Class supportJavaTypeKey() { return Long.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public Long convertToJavaData(ReadCellData> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return Convert.toLong(cellData.getData()); } @Override public WriteCellData
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.test.anod.excel.FileUtils;
import com.test.anod.excel.StringUtils;
import com.test.anod.excel.convert.ExcelBigNumberConvert;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ExcelUtil {
public static void exportExcel(List list, String sheetName, Class clazz, HttpServletResponse response) {
try {
String filename = encodingFilename(sheetName);
response.reset();
FileUtils.setAttachmentResponseHeader(response, filename);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
ServletOutputStream os = response.getOutputStream();
EasyExcel.write(os, clazz)
.autoCloseStream(false)
// 自动适配
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
// 大数值自动转换 防止失真
.registerConverter(new ExcelBigNumberConvert())
.sheet(sheetName).doWrite(list);
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
}
}
public static String encodingFilename(String filename) {
return IdUtil.fastSimpleUUID() + "_" + filename + ".xlsx";
}
}
4.创建(修改)导出对象模板类
说明:
在根据此模板生成excel时,会把所有属性按照属性名都添加到表头中生成表头,再把数据一一对应的循环加入到每一行中
注意:
- 要在类的最上方加上@ExcelIgnoreUnannotated 注解。这个注解的意思是:忽略不加@ExcelProperty的字段进行输出
- @ExcelProperty(value = “用户id”) 此注解加到属性名称上,就会根据 value生成sheetName的列名
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
@Data
@ExcelIgnoreUnannotated
public class UserVo implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id",type = IdType.AUTO)
@ExcelProperty(value = "用户id")
private Integer id;
@ExcelProperty(value = "用户名称")
private String userName;
@ExcelProperty(value = "用户账号")
private String userAccount;
@ExcelProperty(value = "用户密码")
private String password;
}
测试
@RequestMapping("/export")
public void export(HttpServletResponse request){
//查出数据 返回模板样式
List userVoList= userService.export();
//调用工具类
ExcelUtil.exportExcel(userVoList,"测试",UserVo.class,request);
//导出模板 list传空
ExcelUtil.exportExcel(new Arraylist<>,"测试",UserVo.class,request);
}
使用easyexcel导入excel
导入excel



