最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

spring?boot?導(dǎo)出數(shù)據(jù)到excel的操作步驟(demo)

 更新時間:2022年03月02日 11:14:03   作者:FY丶  
這篇文章主要介紹了spring?boot?導(dǎo)出數(shù)據(jù)到excel的實現(xiàn)步驟,文中通過打開一個平時練習使用的springboot的demo給大家詳細介紹,需要的朋友可以參考下

問題來源:

前一段時間公司的項目有個導(dǎo)出數(shù)據(jù)的需求,要求能夠?qū)崿F(xiàn)全部導(dǎo)出也可以多選批量導(dǎo)出(雖然不是我負責的,我自己研究了研究),我們的項目是xboot前后端分離系統(tǒng),后端的核心為SpringBoot 2.2.6.RELEASE,因此今天我主要講述后端的操作實現(xiàn),為了簡化需求,我將需要導(dǎo)出的十幾個字段簡化為5個字段,導(dǎo)出的樣式模板如下:

實現(xiàn)步驟:

打開一個你平時練習使用的springboot的demo,開始按照以下步驟加入代碼進行操作。

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 每列的標題名
     * @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)建標題行
            Row titleRow = sheet1.createRow(excelRow++);
            for(int i = 0;i<columnList.size();i++){
                //創(chuàng)建該行下的每一列,并寫入標題數(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 = "唯一標識")
    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 = "項目編號")
    private String itemNo;
    @ApiModelProperty(value = "項目名稱")
    private String itemName;
     
    @ApiModelProperty(value = "刪除標志 默認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("序號","項目編碼", "項目名稱", "創(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的話也可以寫個簡單的頁面進行測試,我是用的是swaager進行的測試,下面就是我測試的結(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死信隊列?DLX?配置和使用思路分析

    Springboot死信隊列?DLX?配置和使用思路分析

    死信隊列簡稱就是DLX,死信交換機和死信隊列和普通的沒有區(qū)別,當消息成為死信后,如果該隊列綁定了死信交換機,則消息會被死信交換機重新路由到死信隊列,本文給大家介紹Springboot死信隊列?DLX的相關(guān)知識,感興趣的朋友一起看看吧
    2022-03-03
  • Spring解決循環(huán)依賴問題的四種方法匯總

    Spring解決循環(huán)依賴問題的四種方法匯總

    這篇文章主要介紹了Spring解決循環(huán)依賴問題的四種方法匯總,本文給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2024-07-07
  • 圖文詳解SpringBoot中Log日志的集成

    圖文詳解SpringBoot中Log日志的集成

    這篇文章主要給大家介紹了關(guān)于SpringBoot中Log日志的集成的相關(guān)資料,文中通過實例代碼以及圖文介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下
    2021-12-12
  • Spring事務(wù)捕獲異常后依舊回滾的解決

    Spring事務(wù)捕獲異常后依舊回滾的解決

    本文主要介紹了Spring事務(wù)捕獲異常后依舊回滾的解決,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • Spring Boot修改啟動端口的方法

    Spring Boot修改啟動端口的方法

    下面小編就為大家?guī)硪黄猄pring Boot修改啟動端口的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • springboot與vue實現(xiàn)簡單的CURD過程詳析

    springboot與vue實現(xiàn)簡單的CURD過程詳析

    這篇文章主要介紹了springboot與vue實現(xiàn)簡單的CURD過程詳析,圍繞springboot與vue的相關(guān)資料展開實現(xiàn)CURD過程的過程介紹,需要的小伙伴可以參考一下
    2022-01-01
  • IDEA個性化設(shè)置注釋模板詳細講解版

    IDEA個性化設(shè)置注釋模板詳細講解版

    IDEA自帶的注釋模板不是太好用,我本人到網(wǎng)上搜集了很多資料系統(tǒng)的整理了一下制作了一份比較完整的模板來分享給大家,下面這篇文章主要給大家介紹了IDEA個性化設(shè)置注釋模板的相關(guān)資料,需要的朋友可以參考下
    2024-01-01
  • Java優(yōu)先隊列(PriorityQueue)重寫compare操作

    Java優(yōu)先隊列(PriorityQueue)重寫compare操作

    這篇文章主要介紹了Java優(yōu)先隊列(PriorityQueue)重寫compare操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • java中Class.getMethods()和Class.getDeclaredMethods()方法的區(qū)別

    java中Class.getMethods()和Class.getDeclaredMethods()方法的區(qū)別

    這篇文章主要介紹了java中Class.getMethods()和Class.getDeclaredMethods()方法的區(qū)別 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-09-09
  • 詳解Java回調(diào)的原理與實現(xiàn)

    詳解Java回調(diào)的原理與實現(xiàn)

    回調(diào)函數(shù),顧名思義,用于回調(diào)的函數(shù)?;卣{(diào)函數(shù)只是一個功能片段,由用戶按照回調(diào)函數(shù)調(diào)用約定來實現(xiàn)的一個函數(shù)?;卣{(diào)函數(shù)是一個工作流的一部分,由工作流來決定函數(shù)的調(diào)用(回調(diào))時機。
    2017-03-03

最新評論

峨眉山市| 聊城市| 洛川县| 崇左市| 尤溪县| 井陉县| 隆回县| 上高县| 新丰县| 和政县| 黑山县| 海盐县| 黄浦区| 陵水| 苏尼特右旗| 宝清县| 遵义县| 西藏| 资溪县| 嘉定区| 保定市| 吐鲁番市| 定襄县| 府谷县| 当雄县| 临泉县| 巴林右旗| 竹北市| 芦山县| 开原市| 察哈| 雅安市| 邯郸市| 巫山县| 玉山县| 台东市| 如皋市| 华坪县| 高邮市| 都江堰市| 庄河市|