Spring boot数据导出(Excel)

HTML添加:

<tr>
         		<td colspan="4">
   				<input type="submit" value="删除" v-on:click="delAll()"><br/><br/></td>
                <td colspan="4"><a href="#" class="easyui-linkbutton" οnclick="downloadfile();">数据导出</a></td>
            </tr>

script中添加:

function downloadfile(){
     window.location.href="/index/UserExcelDownloads";
 }

控制器端:

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

        List<News> classmateList = newsService.findAll();

        String fileName = "news"  + ".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 (News news : classmateList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(news.getNid());
            row1.createCell(1).setCellValue(news.getTitle());
            row1.createCell(2).setCellValue(news.getContent());
            row1.createCell(3).setCellValue(news.getAddtime());
            row1.createCell(4).setCellValue(news.getAuthor());
            row1.createCell(5).setCellValue(news.getU_id());
            row1.createCell(6).setCellValue(news.getC_id());
            rowNum++;
        }

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

pom文件中加入:

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
		<dependency>
		<groupId>org.apache.poi</groupId>
		<artifactId>poi</artifactId>
		<version>3.6</version>
		</dependency>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章