首頁 > 軟體

spring boot 匯出資料到excel的操作步驟(demo)

2022-03-02 13:00:55

問題來源:

前一段時間公司的專案有個匯出資料的需求,要求能夠實現全部匯出也可以多選批次匯出(雖然不是我負責的,我自己研究了研究),我們的專案是xboot前後端分離系統,後端的核心為SpringBoot 2.2.6.RELEASE,因此今天我主要講述後端的操作實現,為了簡化需求,我將需要匯出的十幾個欄位簡化為5個欄位,匯出的樣式模板如下:

實現步驟:

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

1.新增maven依賴

<!--Excel-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11</version>
</dependency>   

poi-ooxml是一個excel表格的操作工具包,處理的單頁資料量也是百萬級別的,因此我們選擇的是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 {
    /**
     * 使用者資訊匯出類
     * @param response 響應
     * @param fileName 檔名
     * @param columnList 每列的標題名
     * @param dataList 匯出的資料
     */
    public static void uploadExcelAboutUser(HttpServletResponse response,String fileName,List<String> columnList,<br>List<List<String>> dataList){
        //宣告輸出流
        OutputStream os = null;
        //設定響應頭
        setResponseHeader(response,fileName);
        try {
            //獲取輸出流
            os = response.getOutputStream();
            //記憶體中保留1000條資料,以免記憶體溢位,其餘寫入硬碟
            SXSSFWorkbook wb = new SXSSFWorkbook(1000);
            //獲取該工作區的第一個sheet
            Sheet sheet1 = wb.createSheet("sheet1");
            int excelRow = 0;
            //建立標題行
            Row titleRow = sheet1.createRow(excelRow++);
            for(int i = 0;i<columnList.size();i++){
                //建立該行下的每一列,並寫入標題資料
                Cell cell = titleRow.createCell(i);
                cell.setCellValue(columnList.get(i));
            }
            //設定內容行
            if(dataList!=null && dataList.size()>0){
                //序號是從1開始的
                int count = 1;
                //外層for迴圈建立行
                for(int i = 0;i<dataList.size();i++){
                    Row dataRow = sheet1.createRow(excelRow++);
                    //內層for迴圈建立每行對應的列,並賦值
                    for(int j = -1;j<dataList.get(0).size();j++){//由於多了一列序號列所以內層迴圈從-1開始
                        Cell cell = dataRow.createCell(j+1);
                        if(j==-1){//第一列是序號列,不是在資料庫中讀取的資料,因此手動遞增賦值
                            cell.setCellValue(count++);
                        }else{//其餘列是資料列,將資料庫中讀取到的資料依次賦值
                            cell.setCellValue(dataList.get(i).get(j));
                        }
                    }
                }
            }
            //將整理好的excel資料寫入流中
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 關閉輸出流
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /*
        設定瀏覽器下載響應頭
     */
    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();
        }
    }
}

網上的excel的工具類有很多,但很多並不是你複製過來就能直接使用的,因此需要我們深究其原理,這樣可以應對不同的場景寫出屬於我們自己的合適的程式碼,這裡就不一一解釋了,程式碼中註釋加的很清楚,有不懂的可以留言評論。

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 = "建立者")
    @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 = "建立時間")
    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("序號","專案編碼", "專案名稱", "建立時間", "建立人");
        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 = "匯出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,甚至你前端技術足夠ok的話也可以寫個簡單的頁面進行測試,我是用的是swaager進行的測試,下面就是我測試的結果了:

到此這篇關於spring boot 匯出資料到excel的文章就介紹到這了,更多相關spring boot匯出資料內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com