springboot实现数据库中数据导出Excel功能

转载自:https://blog.csdn.net/wilson_m/article/details/79021458

感谢原创作者!


步骤解析

        
1. 前台页面添加数据导出按钮。
 
        
2. 后台进行数据的导出功能。
 
        2. 1 数据库信息的查询。 
        将数据库中的某张表中的数据进行一个查询,将查询到的数据进行写入excel文件中。

        2. 2 建立一张excel表进行存储查询到的数据。 
        建立一张excel表,首先建立一个工作簿,然后建立一个sheet,在sheet中建立一行作为表头,将数据库查询到的数据分别放到对应的表头的下方。

代码

       前台html页面代码如下:


<table border="0" style="margin-top:4px; margin-left: 18px">
            <tr>
                <td><a href="#" class="easyui-linkbutton" onclick="downloadfile();">数据导出</a></td>

            </tr>

        </table>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

       前台页面js代码如下:

function downloadfile(){
        window.location.href="/UserExcelDownloads";
    }
  • 1
  • 2
  • 3

       service和mapper层代码如下:

//mapper接口代码
@Select("select * from teacher")
    public List<Teacher> teacherinfor();

//service层代码
public List<Teacher> teacherinfor(){
        return teachermapper.teacherinfor();

//同时要建立一个Teacher实体类,类中存放的属性名要和导出的数据库中的表的属性名一样
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

       后台Controller层代码如下:

@RequestMapping(value = "UserExcelDownloads", method = RequestMethod.GET)
    public void downloadAllClassmate(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");

        List<Teacher> classmateList = teacherservice.teacherinfor();

        String fileName = "userinf"  + ".xls";//设置要导出的文件的名字
        //新增数据行,并且设置单元格数据

        int rowNum = 1;

        String[] headers = { "学号", "姓名", "身份类型", "登录密码"};
        //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 (Teacher teacher : classmateList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(teacher.getTno());
            row1.createCell(1).setCellValue(teacher.getTname());
            row1.createCell(2).setCellValue(teacher.getType());
            row1.createCell(3).setCellValue(teacher.getTpassword());
            rowNum++;
        }

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

猜你喜欢

转载自blog.csdn.net/debugbugbg/article/details/80962396
今日推荐