文件下载 笔记

导入支持包

        <!--POI 的支持jar-->
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
        </dependency>

代码

    private final IBuildingService iBuildingService;

    @Autowired
    public TestPoiController(IBuildingService iBuildingService) {
        this.iBuildingService = iBuildingService;
    }

    @GetMapping("/testPoi01")
    public void testExecutePoi(HttpServletResponse httpServletResponse){
        List<BuildingEntity> list =  iBuildingService.list();
        //1.在内存中创建一个excel文件
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        //2.创建工作簿
        HSSFSheet sheet = hssfWorkbook.createSheet();
        //3.创建标题行
        HSSFRow titlerRow = sheet.createRow(0);
        titlerRow.createCell(0).setCellValue("宿舍楼编号");
        titlerRow.createCell(1).setCellValue("内含房间数");
        titlerRow.createCell(2).setCellValue("宿舍楼层数");
        titlerRow.createCell(3).setCellValue("应当住宿数");

        //4.遍历数据,创建数据行
        for (BuildingEntity BuildingEntity : list) {
            //获取最后一行的行号
            int lastRowNum = sheet.getLastRowNum();
            HSSFRow dataRow = sheet.createRow(lastRowNum + 1);
            dataRow.createCell(0).setCellValue(BuildingEntity.getBuildingNumber());
            dataRow.createCell(1).setCellValue(BuildingEntity.getBuildingDormTotal());
            dataRow.createCell(2).setCellValue(BuildingEntity.getBuildingFloorTotal());
            dataRow.createCell(3).setCellValue(BuildingEntity.getBuildingShouldPeople());

        }
        //5.创建文件名
        String fileName = "test1.xls";

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            hssfWorkbook.write(fos);
            fos.flush();
            fos.close();
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

        try {
            httpServletResponse.setContentType("application/vnd.ms-excel");
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
            OutputStream outputStream = httpServletResponse.getOutputStream();
            hssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容