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>

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