Springboot 后端下载excel文件

maven依赖

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.1.2</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.1.2</version>
</dependency>
class Person{
    private String name;
    private String age;
    private String phoneNum;
}
@GetMapping("/download")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //读取数据库中所有符合查询条件的数据
        List<Person> list =  service.getAll();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("表名"+end+".xlsx", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        exportExcel(list, outputStream);

        outputStream.flush();
        outputStream.close();
    }
private void exportExcel(List<Person> list, OutputStream outputStream) throws IOException {
        //新建Excel和sheet
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        //设置单元格格式
        CellStyle cellStyle = workbook.createCellStyle();
        //左右居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置表头
        Row forthRow = sheet.createRow(0);
        Cell CellA1 = forthRow.createCell(0);
        CellA1.setCellValue("名称");
        Cell CellB1 = forthRow.createCell(1);
        CellB1.setCellValue("年龄");
        Cell CellC1 = forthRow.createCell(2);
        CellC1.setCellValue("电话");

        // 设置单元格样式 - 日期格式
        CellStyle dateCellStyle = workbook.createCellStyle();
        dateCellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
        //导入数据
        int rownum = 1;
        for (Person p: list) {
            XSSFRow row = sheet.createRow(rownum++);
            row.createCell(0).setCellValue(p.getName());
            row.createCell(1).setCellValue(p.getAge());
            row.createCell(2).setCellValue(p.getPhoneNum());
        }
        workbook.write(outputStream);
    }
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐