方法实现:通过继承接口实现EasyExcel的registerWriteHandler方法实现自定义样式,表头和内容都适用,这里只有表头代码
实体类
package cn.xwl.easyexcel.dto;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1602341773222025686L;
@ExcelProperty(index = 0, value = {"姓名"})
private String name;
@ExcelProperty(index = 1, value = {"年龄"})
private Integer age;
@ExcelProperty(index = 2, value = {"家庭地址"})
private String address;
}
controller
@GetMapping("/download")
public void importPrisonerDownload(HttpServletResponse response) throws Exception {
try{
String fileName = URLEncoder.encode("用户信息", "UTF-8").replaceAll("\\+", "%20");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");//设置响应头
response.setHeader("mime","application/vnd.ms-excel");
List<User> lst = new ArrayList<>();//空数组作为导入模板 可以再写一个方法给数组赋值作为导出模板
//表头字体颜色map 1为user中索引位置
Map<Integer,Short> colorMap=new HashMap<>();
colorMap.put(1, IndexedColors.BLUE.index);
EasyExcel.write(response.getOutputStream(), User.class)
.registerWriteHandler(new XCellStyle(colorMap))
.sheet("User")
.doWrite(lst);
}catch (Exception e){
e.printStackTrace();
}
}
工具类
package cn.xwl.easyexcel.util;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.util.HashMap;
import java.util.Map;
/*
EasyExcel 表格样式工具类
*/
public class XCellStyle extends AbstractVerticalCellStyleStrategy {
//key为ExcelProperty value为颜色
public Map<Integer,Short> colorMap=new HashMap<>();
public XCellStyle(Map<Integer,Short> colorMap){
this.colorMap=colorMap;
}
//表格头样式
@Override
protected WriteCellStyle headCellStyle(Head head) {
WriteCellStyle writeCellStyle=new WriteCellStyle();
WriteFont font=new WriteFont();
//自定义字体颜色
for(Integer key:colorMap.keySet()){
if(head.getColumnIndex()==key){
font.setColor(colorMap.get(key));
break;
}else {
font.setColor(IndexedColors.BLACK.index);//默认颜色
}
}
//有兴趣可以自己定义别的这里只定义了color
writeCellStyle.setWriteFont(font);
return writeCellStyle;
}
//单元格格内样式 写法与上面类似
@Override
protected WriteCellStyle contentCellStyle(Head head) {
return null;
}
}