欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用Java将数据库的数据导出至Excel表中

程序员文章站 2024-03-21 08:37:16
...

步骤一:先引入依赖包

 <!--Excel的导出-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

步骤二:在controller添加如下代码

 /**
     * 导出用户数据到Excel
     * @param response
     * @throws IOException
     */
    @RequestMapping("/ExcelDownload")
    public void downloadAllClassmate(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");

        List<User> userList = userInfoService.queryUser();
        String fileName = "userinf"  + ".xls";//设置要导出的文件的名字
        //新增数据行,并且设置单元格数据

        int rowNum = 1;

        String[] headers = { "Id", "姓名", "密码", "手机号"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (User user : userList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(user.getId());
            row1.createCell(1).setCellValue(user.getUsername());
            row1.createCell(2).setCellValue(user.getPassword());
            row1.createCell(3).setCellValue(user.getMobile());
            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }