1.添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
2.创建ExcelController类
//interviewerService是获取数据集合(excel中展示的数据)
@Autowired
private InterviewerServiceinterviewerService;
@GetMapping("/getExcel")
@ResponseBody
public void getExcel(HttpServletResponse response) {
//获取集合
List<Interviewer> interviewerList =interviewerService.getInterviewer();
HSSFWorkbook workbook =new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
int rowNum =0;
//自定义列标题
String[] headers ={"姓名","性别","职位"};
HSSFRow row = sheet.createRow(rowNum);
for (int i =0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text =new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
for (Interviewer inter : interviewerList) {
rowNum++;
HSSFRow row1 = sheet.createRow(rowNum);
row1.createCell(0).setCellValue(inter.getName());
row1.createCell(1).setCellValue(inter.getSex());
row1.createCell(2).setCellValue(inter.getPosition());
}
if (workbook !=null) {
try {
String fileName ="报名人员" +".xls";
//下载后的excel名称可以为中文
String downloadFileName =new String(fileName.getBytes("UTF-8"),"iso-8859-1");
String headStr ="attachment; filename=\"" + downloadFileName +"\"";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
}