用Apache开源框架poi,或则jxl都可以实现,面向百度编程,把代码copy下来,根据自己的业务改一下,便可拿来用
但是这样的代码又臭又长
使用Apache poi,jxl的缺点
传统excel框架的不足除了又臭又长,不够简单快速外,还存在一个严重的问题,就是非常耗内存,严重时会导致内存溢出
POI虽然是excel解析框架中被使用最广泛的,但该框架并不完美
开发者们大部分使用 POI,都是使用其 userModel 模式。而 userModel 的好处是上手容易使用简单,随便拷贝个代码跑一下,剩下就是写业务转换了,虽然转换也要写上百行代码,但是还是可控的。
然而 userModel 模式最大的问题是在于,对内存消耗非常大,一个几兆的文件解析甚至要用掉上百兆的内存。现实情况是,很多应用现在都在采用这种模式,之所以还正常在跑是因为并发不大,并发上来后,一定会OOM或者频繁的 full gc。
阿里出品的 EasyExcel 非常简单快速好用
什么是 EasyExcel? 见名知意,就是让你操作 Excel 异常的酸爽。先来看下 EasyExcel GitHub
<!--alibaba easyexcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beta5</version>
</dependency>
package com.linln.admin.excel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.linln.modules.system.domain.Two;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @Author zhao
* @create 2019/6/14 16:06
*/
public class WriteExcel {
public static void main(String[] args) throws IOException {
excel();
}
public static void excel() throws IOException {
//文件输出位置
OutputStream outputStream = new FileOutputStream("D:\\huankeyun\\1438\\test.xls");
ExcelWriter excelWriter = EasyExcelFactory.getWriter(outputStream);
//写仅有一个Sheet的Excel文件,此场景较为通用
Sheet sheet = new Sheet(1, 0, Two.class);
//第一个sheet名称
sheet.setSheetName("第一个sheet");
//写数据到Writer上下文中
//参数1:创建要写入的模型数据
//参数2:要写入的目标 sheet
excelWriter.write(createModelList(), sheet);
//将上下文中的最终输出流写入到指定文件中
excelWriter.finish();
//关闭流
outputStream.close();
}
public static List<Two> createModelList() {
List<Two> twos = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Two two = Two.builder().title("标题1" + i).remark("zhao").build();
twos.add(two);
}
return twos;
}
}
package com.linln.modules.system.domain;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.StatusUtil;
import com.linln.modules.system.domain.User;
import lombok.Builder;
import lombok.Data;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.annotations.Where;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
impo