本文摘要
文中介绍了便捷Excel轮子easypoi,特点及使用方法,以及如何实现Excel多Sheet的导出功能
前言
Excel 作为开发中常用功能,经常需要用到,小老弟找了网上一些多Sheet导出的实现,都不太满意,因此根据EasyPoi的说明文档写了一个工具类,在这里和大家分享
EasyPoi和阿里的EasyExcel都有用过,是为便捷操作Excel的开源轮子,基于不重复造的原则,小老弟对使用较多的easyPoi进行本文所需功能的实现
EasyPoi支持如下
功能列表 | 详细 |
---|---|
Excel导入 | 注解导入 && Map导入 && 大数据量导入sax模式 && 导入文件保存 && 文件校验 && 字段校验 |
Excel导出 | 注解导出 && 模板导出 && html导出,Excel自适应xls和xlsx两种格式 |
Excel转html | |
word导出 | word只支持docx模式 |
pdf导出 |
准备工作
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
多sheet的Excel导出
生成workbook关键代码
/**
* 创建workbook,
* 通过maplist填充Excel内容
* 返回workbook
*
* 进一步使用可以写入流,e.g.
* FileOutputStream fos = new FileOutputStream(file);
* workbook.write(fos);
* */
public static Workbook mutiSheet(List<Map<String, Object>> mapListList){
Workbook workbook = null;
workbook = ExcelExportUtil.exportExcel(mapListList,ExcelType.XSSF);
return workbook;
}
多sheet工具类WorkBookUtils
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.jdcloud.task.domain.vo.wenxian.IndustryStoreMomFungi;
import org.apache.poi.ss.usermodel.Workbook;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WorkBookUtils {
/**
* 创建workbook,
* 通过maplist填充Excel内容
* 返回workbook
*
* 进一步使用可以写入流,e.g.
* FileOutputStream fos = new FileOutputStream(file);
* workbook.write(fos);
* */
public static Workbook mutiSheet(List<Map<String, Object>> mapListList){
Workbook workbook = null;
workbook = ExcelExportUtil.exportExcel(mapListList,ExcelType.XSSF);
return workbook;
}
public static Map<String, Object> createOneSheet(ExportParams exportParams,Class<?> clazz,List<?> data){
Map<String, Object> map = new HashMap<>();
map.put("title",exportParams);//new ExportParams("title"+i, "sheetName"+i, ExcelType.XSSF)
map.put("entity", clazz);
map.put("data",data);
return map;
}
/*
* 创建一个表格并填充内容
* 返回map供工作簿使用
* */
public static Map<String, Object> createOneSheet(String sheetName,String title,Class<?> clazz,List<?> data){
ExportParams exportParams = new ExportParams(title,sheetName, ExcelType.XSSF);
return createOneSheet(exportParams,clazz,data);
}
}
service
/**
* 将数据存储进response,调用接口就能下载文件
* */
public void exportData(HttpServletRequest request, HttpServletResponse response ) throws URISyntaxException, IOException {
String fileName="data.xlsx";
File file = createDatafile(fileName);
Object data=null;
fillData(file,data);
datatoResponse(request,response,file,fileName);
}
/**
* 将数据存储进response,调用接口就能下载文件
* */
private void datatoResponse(HttpServletRequest request, HttpServletResponse response,File file,String fileName) throws IOException {
OutputStream out = null;
FileInputStream in = null;
try {
// 1.读取要下载的内容
in = new FileInputStream(file);
// 2. 告诉浏览器下载的方式以及一些设置
// 解决文件名乱码问题,获取浏览器类型,转换对应文件名编码格式,IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
String agent = request.getHeader("user-agent");
if (agent.contains("FireFox")) {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
} else {
fileName = URLEncoder.encode(fileName, "UTF-8");
}
// 设置下载文件的mineType,告诉浏览器下载文件类型
String mineType = request.getServletContext().getMimeType(fileName);
response.setContentType(mineType);
// 设置一个响应头,无论是否被浏览器解析,都下载
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
// 将要下载的文件内容通过输出流写到浏览器
out = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
}
/**
* 设置文件路径 && 保证文件对象的正确打开
* */
private File createDatafile(String fileName) throws URISyntaxException, IOException {
File file = null;
String resource = this.getClass().getClassLoader().getResource("").getPath()+fileName;
URI uri = new URI(resource);
File myFile = new File(resource);//创建File对象,参数为String类型,表示目录名
//判断文件是否存在,如不存在则调用createNewFile()创建新目录,否则跳至异常处理代码
if(!myFile.exists()) myFile.createNewFile();
System.out.println("文件创建成功");
return myFile;
}
private File fillData(File savefile,Object data) throws IOException {
List<Map<String, Object>> lists = new ArrayList<>();
//sheet1
List<Map<String, String>> datas1 = excelDao.queryTableColumns("whole_network_wenxian_region_trend_info");
Map<String, Object> temp1 = WorkBookUtils.createOneSheet("表1", "表头大标题", Map.class, datas1);
lists.add(temp1);
//sheet2
List<Map<String, String>> datas2 = excelDao.queryTableColumns("whole_network_wenxian_industry_trend");
Map<String, Object> temp2 = WorkBookUtils.createOneSheet("表2", "表头大标题", Map.class, datas2);
lists.add(temp2);
Workbook workbook = WorkBookUtils.mutiSheet(lists);
FileOutputStream fos = new FileOutputStream(savefile);
workbook.write(fos);
fos.close();
return savefile;
}
controller
@RequestMapping("/export")
public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
excelService.exportData(request,response);
}