照例先看controller
@PostMapping("/exportPerson")
public void exportPerson(HttpServletResponse response) throws IOException {
contactsService.exportContactsExcel(response, groupId);
}
service不用记了,直接看impl
将person的list转化成personVO,丢给导出类
public void exportPersonsExcel(HttpServletResponse response) throws IOException {
List<Person> persons = personMapper.listPersons();
List<PersonVO> personVOS = new ArrayList<>();
persons.forEach(p -> {
PersonVO pv = new PersonVO(p.getName(), p.getAge(), p.getSex());
personVOS.add(pv);
});
ExportExcel<PersonVO> exprot = new ExportExcel<>(response, PersonVOS, "联系人名单", PersonVO.class);
exprot.exportExcel();
}
PersonVO没什么好记的
上述导出的过程调用了导出类,记一下导出的实现
import com.alibaba.excel.EasyExcel;
import lombok.AllArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@AllArgsConstructor
public class ExportExcel<E> {
private final HttpServletResponse response;
private final List<E> eList;
private final String fileName;
private final Class<E> eClass;
public void exportExcel() throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
String exportName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + exportName + "\"");
EasyExcel.write(response.getOutputStream(), eClass).sheet(fileName).doWrite(eList);
}
}
后续不论需要导出什么台帐,只需要做好vo的list直接丢给导出类即可,具有通用性,也方便扩展和管理
- 后记
记一个小问题,在做PersonVO导出实体时,要记加 @AllArgsConstructor 和 @Data,否则会报错或导致导出台帐为空白文件