最简单的写

实体类

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ContentRowHeight(15) //设定每一行的高度,不包含表头
@HeadRowHeight(30) //设置 表头 高度
public class ExcelData extends BaseRowModel implements Serializable
{
@ColumnWidth(15) //列宽
@ExcelProperty("姓名")
private String userName;

@ColumnWidth(15)
@ExcelProperty("出生日期")
@DateTimeFormat("yyyy-MM-dd") // "yyyy/MM/dd" "yyyy年MM月dd日HH时mm分ss秒" 等等格式都可以
private String birth;

@ColumnWidth(15)
@ExcelProperty("工资")
@NumberFormat(".##") //#代表任意数字, 注意这里的日期格式和数字格式都必须是字符串类型的
private String salary;
}

指定写入的列

@Data
public class IndexData {
@ExcelProperty(value = "字符串标题", index = 0)
private String string;
@ExcelProperty(value = "日期标题", index = 1)
private Date date;
/**
* 这里设置3 会导致第二列空的
*/
@ExcelProperty(value = "数字标题", index = 3)
private Double doubleData;
}

复杂头写入

@Data
public class ComplexHeadData {
@ExcelProperty({"主标题", "字符串标题"})
private String string;
@ExcelProperty({"主标题", "日期标题"})
private Date date;
@ExcelProperty({"主标题", "数字标题"})
private Double doubleData;
}

EasyExcelUtil

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
版本2.1.7 工具类(仅导出)中可自定义样式格式等
**/
@Component
public class EasyExcelUtil {

/**
* 导出 Excel :一个 sheet,带表头.
*
* @param response HttpServletResponse
* @param data 数据 list,每个元素为一个 BaseRowModel
* @param fileName 导出的文件名
* @param sheetName 导入文件的 sheet 名
* @param model 映射实体类,Excel 模型
* @throws Exception 异常
*/
public void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class model) throws Exception {

// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//设置表头居中对齐
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 颜色
headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 10);
// 字体
headWriteCellStyle.setWriteFont(headWriteFont);
headWriteCellStyle.setWrapped(true);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//设置内容靠中对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(getOutputStream(fileName, response), model).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy)
//最大长度自适应 目前没有对应算法优化 建议注释掉不用 会出bug
// .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.doWrite(data);

}

/**
* 导出文件时为Writer生成OutputStream.
*
* @param fileName 文件名
* @param response response
* @return ""
*/
private OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
return response.getOutputStream();
} catch (IOException e) {
throw new Exception("导出excel表格失败!", e);
}
}

}

控制层

import com.alibaba.excel.util.CollectionUtils;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Api(tags = "数据导出--Excel")
@Controller
@RequestMapping("/export")
public class ExportController
{
@Autowired
private UserMapper userMapper;

@Autowired
private EasyExcelUtil excelUtil;

@ApiOperation("数据导出")
@GetMapping("/exportExcel")
public void exportSysSystemExcel(HttpServletResponse response) throws Exception {
try {
// 查询总数并封装相关变量
Integer totalRowCount = (int) userMapper.selectNormalUserCount();
Integer pageSize = ExcelConstant.PER_WRITE_ROW_COUNT;
Integer writeCount = totalRowCount % pageSize == 0 ? (totalRowCount / pageSize) : (totalRowCount / pageSize + 1);

// 写数据
for (int i = 0; i < writeCount; i++) {
List<List<String>> dataList = new ArrayList<>();
//查询并封装数据
PageHelper.startPage(i + 1, pageSize);

List<User> userList = userMapper.selectNormalUser();
if (!CollectionUtils.isEmpty(userList)) {
userList.forEach(item -> {
dataList.add(Arrays.asList(
user.getBirthday() == null? "无" : user.getBirthday(),
user.getBirthday() == null? "无" : user.getBirthday(),
user.getSalary() == null? "无" : user.getSalary()
));
});
}
excelUtil.writeExcel(response, dataList, "文件名称", "sheet1", ExcelData.class);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}