spring?boot?導(dǎo)出數(shù)據(jù)到excel的操作步驟(demo)
問題來源:
前一段時間公司的項(xiàng)目有個導(dǎo)出數(shù)據(jù)的需求,要求能夠?qū)崿F(xiàn)全部導(dǎo)出也可以多選批量導(dǎo)出(雖然不是我負(fù)責(zé)的,我自己研究了研究),我們的項(xiàng)目是xboot前后端分離系統(tǒng),后端的核心為SpringBoot 2.2.6.RELEASE,因此今天我主要講述后端的操作實(shí)現(xiàn),為了簡化需求,我將需要導(dǎo)出的十幾個字段簡化為5個字段,導(dǎo)出的樣式模板如下:
實(shí)現(xiàn)步驟:
打開一個你平時練習(xí)使用的springboot的demo,開始按照以下步驟加入代碼進(jìn)行操作。
1.添加maven依賴
<!--Excel--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.11</version> </dependency>
poi-ooxml是一個excel表格的操作工具包,處理的單頁數(shù)據(jù)量也是百萬級別的,因此我們選擇的是poi-ooxml.
2.編寫excel工具類
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.List; public class ExcelUtil { /** * 用戶信息導(dǎo)出類 * @param response 響應(yīng) * @param fileName 文件名 * @param columnList 每列的標(biāo)題名 * @param dataList 導(dǎo)出的數(shù)據(jù) */ public static void uploadExcelAboutUser(HttpServletResponse response,String fileName,List<String> columnList,<br>List<List<String>> dataList){ //聲明輸出流 OutputStream os = null; //設(shè)置響應(yīng)頭 setResponseHeader(response,fileName); try { //獲取輸出流 os = response.getOutputStream(); //內(nèi)存中保留1000條數(shù)據(jù),以免內(nèi)存溢出,其余寫入硬盤 SXSSFWorkbook wb = new SXSSFWorkbook(1000); //獲取該工作區(qū)的第一個sheet Sheet sheet1 = wb.createSheet("sheet1"); int excelRow = 0; //創(chuàng)建標(biāo)題行 Row titleRow = sheet1.createRow(excelRow++); for(int i = 0;i<columnList.size();i++){ //創(chuàng)建該行下的每一列,并寫入標(biāo)題數(shù)據(jù) Cell cell = titleRow.createCell(i); cell.setCellValue(columnList.get(i)); } //設(shè)置內(nèi)容行 if(dataList!=null && dataList.size()>0){ //序號是從1開始的 int count = 1; //外層for循環(huán)創(chuàng)建行 for(int i = 0;i<dataList.size();i++){ Row dataRow = sheet1.createRow(excelRow++); //內(nèi)層for循環(huán)創(chuàng)建每行對應(yīng)的列,并賦值 for(int j = -1;j<dataList.get(0).size();j++){//由于多了一列序號列所以內(nèi)層循環(huán)從-1開始 Cell cell = dataRow.createCell(j+1); if(j==-1){//第一列是序號列,不是在數(shù)據(jù)庫中讀取的數(shù)據(jù),因此手動遞增賦值 cell.setCellValue(count++); }else{//其余列是數(shù)據(jù)列,將數(shù)據(jù)庫中讀取到的數(shù)據(jù)依次賦值 cell.setCellValue(dataList.get(i).get(j)); } } } } //將整理好的excel數(shù)據(jù)寫入流中 wb.write(os); } catch (IOException e) { e.printStackTrace(); } finally { try { // 關(guān)閉輸出流 if (os != null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } } /* 設(shè)置瀏覽器下載響應(yīng)頭 */ private static void setResponseHeader(HttpServletResponse response, String fileName) { try { try { fileName = new String(fileName.getBytes(),"ISO8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } response.setContentType("application/octet-stream;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename="+ fileName); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); } } }
網(wǎng)上的excel的工具類有很多,但很多并不是你復(fù)制過來就能直接使用的,因此需要我們深究其原理,這樣可以應(yīng)對不同的場景寫出屬于我們自己的合適的代碼,這里就不一一解釋了,代碼中注釋加的很清楚,有不懂的可以留言評論。
3.編寫controller,service,serviceImpl,dao,entity
3.1 entity
import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.hibernate.annotations.Where; import javax.persistence.*; import java.math.BigDecimal; @Data @Entity @Where(clause = "del_flag = 0") @Table(name = "t_scf_item_data") public class ItemData{ private static final long serialVersionUID = 1L; @Id @TableId @ApiModelProperty(value = "唯一標(biāo)識") private String id = String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()); @ApiModelProperty(value = "創(chuàng)建者") @CreatedBy private String createBy; @CreatedDate @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @ApiModelProperty(value = "創(chuàng)建時間") private Date createTime; @ApiModelProperty(value = "項(xiàng)目編號") private String itemNo; @ApiModelProperty(value = "項(xiàng)目名稱") private String itemName; @ApiModelProperty(value = "刪除標(biāo)志 默認(rèn)0") private Integer delFlag = 0; }
3.2 dao
import cn.exrick.xboot.modules.item.entity.ItemData; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ItemDataDao{ @Query(value = "select a.item_no,a.item_name,concat(a.create_time),a.create_by from t_scf_item_data a where a.del_flag = 0 limit 5",nativeQuery = true) List<List<String>> findAllObject(); @Query(value = "select a.item_no,a.item_name,concat(a.create_time),a.create_by from t_scf_item_data a where a.del_flag = 0 and a.id in ?1 limit 5",nativeQuery = true) List<List<String>> findByIds(List<String> idList); }
3.3 service
import javax.servlet.http.HttpServletResponse; import java.util.List; public interface TestService { void exportExcel(List<String> idList, HttpServletResponse response); }
3.4 serviceImpl
import cn.exrick.xboot.common.utils.ExcelUtil; import cn.exrick.xboot.modules.item.dao.ItemDataDao; import cn.exrick.xboot.modules.item.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Transactional @Service public class TestServiceImpl implements TestService { @Autowired private ItemDataDao itemDataDao; @Override public void exportExcel(List<String> idList, HttpServletResponse response) { List<List<String>> dataList = new ArrayList<>(); if(idList == null || idList.size() == 0){ dataList = itemDataDao.findAllObject(); }else{ dataList = itemDataDao.findByIds(idList); } List<String> titleList = Arrays.asList("序號","項(xiàng)目編碼", "項(xiàng)目名稱", "創(chuàng)建時間", "創(chuàng)建人"); ExcelUtil.uploadExcelAboutUser(response,"apply.xlsx",titleList,dataList); } }
3.5 controller
import cn.exrick.xboot.modules.item.service.TestService; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.Map; @Slf4j @RestController @RequestMapping("/test") public class TestController { @Autowired private TestService testService; @RequestMapping(value = "/exportExcel", method = RequestMethod.POST) @ApiOperation(value = "導(dǎo)出excel",produces="application/octet-stream") public void exportCorpLoanDemand(@RequestBody Map<String,List<String>> map, HttpServletResponse response){ ; log.info("測試:{}",map); testService.exportExcel(map.get("list"),response); } }
4.測試
測試的話可以使用swagger或者postman,甚至你前端技術(shù)足夠ok的話也可以寫個簡單的頁面進(jìn)行測試,我是用的是swaager進(jìn)行的測試,下面就是我測試的結(jié)果了:
到此這篇關(guān)于spring boot 導(dǎo)出數(shù)據(jù)到excel的文章就介紹到這了,更多相關(guān)spring boot導(dǎo)出數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot整合Mongodb實(shí)現(xiàn)增刪查改的方法
這篇文章主要介紹了SpringBoot整合Mongodb實(shí)現(xiàn)簡單的增刪查改,MongoDB是一個以分布式數(shù)據(jù)庫為核心的數(shù)據(jù)庫,因此高可用性、橫向擴(kuò)展和地理分布是內(nèi)置的,并且易于使用。況且,MongoDB是免費(fèi)的,開源的,感興趣的朋友跟隨小編一起看看吧2022-05-05Spring boot 總結(jié)之跨域處理cors的方法
本篇文章主要介紹了Spring boot 總結(jié)之跨域處理cors的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02詳解java 三種調(diào)用機(jī)制(同步、回調(diào)、異步)
這篇文章主要介紹了java 三種調(diào)用機(jī)制(同步、回調(diào)、異步),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04