导出Excel
方法一
导入EasyExcel依赖
<!-- 导出excel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
</dependency>
创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderExcel {
//订单号
@ExcelProperty("订单编号")
private long orderId;
//xxxxxx
}
OrderServiceImpl
public void excelWrite(){
//1、创建一个文件对象
File excelFile = new File("E:/Order.xlsx");
//2、判断文件是否存在,不存在则创建一个Excel文件
if (!excelFile.exists()) {
try {
excelFile.createNewFile();//创建一个新的文件
} catch (IOException e) {
e.printStackTrace();
}
}
//3、指定需要那个class去写。然后写到第一个sheet,名字为模版,然后文件流会自动关闭
EasyExcel.write(excelFile, OrderExcel.class).sheet("订单模版").doWrite(queryToExcel());
}
public List<OrderExcel> queryToExcel() {
//业务代码,获取数据集
List<Order> orders = xxxxxx.xxxxxx(xxxxxx);
List<OrderExcel> excels = new ArrayList<>();
//遍历数据集,导出Excel
for (int i = 0; i < orders.size(); i++) {
Order order = orders.get(i);
OrderExcel data = new OrderExcel();
data.setOrderId(order.getOrderId());
excels.add(data);
}
return excels;
}
如果希望多个sheet导出那么可以
public String toExcel(String b, String s, String e ,String filePath) {
//业务代码
//xxxxxx
//1、创建一个文件对象
// 输出流
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(new File(filePath));
//3、指定需要那个class去写。然后写到第i个sheet
ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
int i=0;
//业务代码
for (xxxxxx) {
List<DataExcel> excels = new ArrayList<>();
//业务代码,将xxxxxx导入到excels中
xxxxxxmap.entrySet().forEach(f->excels.add(new DataExcel(f.getKey(),f.getValue())));
//不同的表数据写在不同的sheet
WriteSheet build = EasyExcel.writerSheet(i, entry.getKey().getGroupName()).head(DataExcel.class).build();
i++;
excelWriter.write(excels,build);
}
excelWriter.finish();
}catch (Exception e){
e.printStackTrace();
}
return "导出Excel成功";
}
测试类
@Test
public void TestToExcel(){
orderService.excelWrite();
}
方法二
导入EasyExcel依赖
<!-- 导出excel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
</dependency>
编写ExcelUtil
@Component
public class ExcelUtil {
public ExcelWriter getExcelWriter(HttpServletResponse response){
//内容样式策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//垂直居中,水平居中
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//设置边框
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
// 字体策略
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short) 12);
contentWriteCellStyle.setWriteFont(contentWriteFont);
//头策略使用默认 设置字体大小
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 12);
headWriteCellStyle.setWriteFont(headWriteFont);
ExcelWriter excelWriter;
//ExcelWriter写入对象
try {
//这是为了导出流,在浏览器下载excel因此选择response.getOutputStream
excelWriter= EasyExcel.write(response.getOutputStream()).registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle,contentWriteCellStyle)).build();
//如果导出到本地
//excelWriter= EasyExcel.write(new FileOutputStream("FilePath")).registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle,contentWriteCellStyle)).build();
return excelWriter;
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
//发送响应流方法,无论是word,excel,text都实用的响应流类
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//浏览器检测文件类型,有两种响应:第一种是MIME(多功能Internet 邮件扩充服务,最早用于邮件系统,后来拓展到浏览器中);
// 另一种,当浏览器无法确定文件类型时,就是application/octet-stream类型。
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
//关闭缓存
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
编写Service层代码
public ExcelWriter toExcel(String c,String u,ExcelWriter excelWriter){
log.info("导出Excel,code:{},userId:{}",code,userId);
//获取表数据
//xxxxxx
//获取表头信息
//业务代码
List<List<String>> titleList = xxxxxx;
//创建表格对象
WriteTable table = new WriteTable();
//设置表头
table.setHead(titleList);
//获取所有表
//xxxxxx
//设置sheet编号
int index = 1;
//遍历多个表,(如果有多个表)
for (T t : TList) {
//根据需要写业务代码
//xxxxxx
//创建Sheet对象
WriteSheet sheet = new WriteSheet();
//设置第N个Sheet
sheet.setSheetNo(index);
//设置Sheet名称
sheet.setSheetName(config.getPositionName());
//获取信息列表
List<List<Object>> contentsList = xxxxxx;
excelWriter.write(contentsList,sheet,table);
index++;
}
log.info("导出成功");
return excelWriter;
}
controller层代码
@PostMapping("futures/toExcel")
public void toExcel(@RequestBody T t, HttpServletResponse response){
//业务代码
//if(xxxxxx){
//xxxxxx
//}
//文件名
String fileName = t+"-"+ DateUtil.date().toDateStr()+".xlsx";
//设置导出流的response信息
excelUtil.setResponseHeader(response,fileName);
ExcelWriter excelWriter = excelUtil.getExcelWriter(response);
String code = baseCondition.getCode();
excelWriter = excelService.toExcel(xxxxxx, xxxxxx,excelWriter);
//释放资源
excelWriter.finish();
}
方法一与方法二都使用了EasyExcel进行Excel的导出,区别在于方法一建立了实体类进行Excel的导出,这样的好处是可以直接使用实体类对象进行数据的导出,每一个列和标题都是对应关系。方法二则直接使用了List来导出,每一行数据作为一个list,这样的好处就是可以设置到每一行的每一列。除此之外,方法二还使用了流进行导出,在网页端点击导出Excel按钮发送请求给后端之后,会弹出下载的文件。