SpringBoot结合poi下载excel文件

1.添加依赖

 

     org.apache.poi

     poi-ooxml

     3.12



2.创建ExcelController类

//interviewerService是获取数据集合(excel中展示的数据)

@Autowired

private InterviewerServiceinterviewerService;


@GetMapping("/getExcel")

@ResponseBody

public void getExcel(HttpServletResponse response) {

//获取集合

    List 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();

}

}

}

你可能感兴趣的:(SpringBoot结合poi下载excel文件)