springboot+vue的文件导出功能

1.html

<input type="button" v-on:click="downloadfile()" class="button bg-main icon-check-square-o" value="导出">

2.vue

downloadfile:function(){
          window.location.href="/news/UserExcelDownloads";
        },

3.controller

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

        List<newsMessage> classmateList = newsMessageService.findAll();

        String fileName = "news"  + ".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 (newsMessage teacher : classmateList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(teacher.getNid());
            row1.createCell(1).setCellValue(teacher.getN_title());
            row1.createCell(2).setCellValue(teacher.getN_content());
            row1.createCell(3).setCellValue(teacher.getN_addtime());
            row1.createCell(4).setCellValue(teacher.getN_author());
            row1.createCell(5).setCellValue(teacher.getN_show());
            rowNum++;
        }

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

你可能感兴趣的:(Java,框架学习)