SpringBoot使用POI進(jìn)行Excel下載
本文實例為大家分享了SpringBoot使用POI進(jìn)行Excel下載的具體代碼,供大家參考,具體內(nèi)容如下
使用poi處理Excel特別方便,此處將處理Excel的代碼分享出來。
1.maven引用
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency>
2.service邏輯代碼
/** * 獲取下載模版 */ public void salaryTemplate(HttpServletResponse response)throws Exception{ HSSFWorkbook workbook = new HSSFWorkbook(); exportExcel(workbook); response.setHeader("Content-type","application/vnd.ms-excel"); // 解決導(dǎo)出文件名中文亂碼 response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition","attachment;filename="+new String("工資模版".getBytes("UTF-8"),"ISO-8859-1")+".xls"); workbook.write(response.getOutputStream()); } //導(dǎo)入為模版 private void exportExcel(HSSFWorkbook workbook) throws Exception { //創(chuàng)建創(chuàng)建sheet HSSFSheet sheet = workbook.createSheet("工資"); //創(chuàng)建單元格樣式 CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index); //設(shè)置首行標(biāo)題標(biāo)題 HSSFRow headerRow = sheet.createRow(0); headerRow.createCell(0).setCellStyle(cellStyle); headerRow.createCell(0).setCellValue("工號"); headerRow.createCell(1).setCellStyle(cellStyle); headerRow.createCell(1).setCellValue("姓名"); headerRow.createCell(2).setCellStyle(cellStyle); headerRow.createCell(2).setCellValue("年齡"); //創(chuàng)建三行數(shù)據(jù) HSSFRow row; for (int i = 0; i <4; i++) { row = sheet.createRow(i + 1); row.createCell(0).setCellStyle(cellStyle); row.createCell(0).setCellValue(i); row.createCell(1).setCellStyle(cellStyle); row.createCell(1).setCellValue("張三"); row.createCell(2).setCellStyle(cellStyle); row.createCell(2).setCellValue(19); } }
3.controller
@GetMapping("/salary/template") public void salaryTemplate(HttpServletResponse response)throws Exception{ salaryService.salaryTemplate(response); }
請求這個接口,下載下來就是Excel文件。寫的比較簡單,不過看代碼基本就能看懂。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Nacos通過RefreshScope實現(xiàn)配置自動更新的方式分享
這篇文章主要給大家介紹了Nacos如何通過RefreshScope實現(xiàn)配置自動更新,文中給了兩種實現(xiàn)方式供大家參考,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-09-09Java使用反射和動態(tài)代理實現(xiàn)一個View注解綁定庫
這篇文章主要介紹了Java使用反射和動態(tài)代理實現(xiàn)一個View注解綁定庫,代碼簡潔,使用簡單,擴(kuò)展性強,結(jié)合實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05Spring?Boot?Actuator管理日志的實現(xiàn)
本文主要介紹了Spring?Boot?Actuator管理日志的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07集合框架(Collections Framework)詳解及代碼示例
這篇文章主要介紹了集合框架(Collections Framework)詳解及代碼示例,文章涉及集合數(shù)組的區(qū)別,collection接口,iterator迭代器,list接口及其用法,LinkedHashSet集合等有關(guān)內(nèi)容,具有一定參考價值,需要的朋友可以了解下。2017-11-11SpringBoot集成Nacos實現(xiàn)注冊中心與配置中心流程詳解
這篇文章主要介紹了SpringBoot集成Nacos實現(xiàn)注冊中心與配置中心流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02