spring?boot?導(dǎo)出數(shù)據(jù)到excel的操作步驟(demo)
問(wèn)題來(lái)源:
前一段時(shí)間公司的項(xiàng)目有個(gè)導(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),為了簡(jiǎn)化需求,我將需要導(dǎo)出的十幾個(gè)字段簡(jiǎn)化為5個(gè)字段,導(dǎo)出的樣式模板如下:

實(shí)現(xiàn)步驟:
打開(kāi)一個(gè)你平時(shí)練習(xí)使用的springboot的demo,開(kāi)始按照以下步驟加入代碼進(jìn)行操作。
1.添加maven依賴
<!--Excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency> poi-ooxml是一個(gè)excel表格的操作工具包,處理的單頁(yè)數(shù)據(jù)量也是百萬(wàn)級(jí)別的,因此我們選擇的是poi-ooxml.
2.編寫(xiě)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)存溢出,其余寫(xiě)入硬盤(pán)
SXSSFWorkbook wb = new SXSSFWorkbook(1000);
//獲取該工作區(qū)的第一個(gè)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)建該行下的每一列,并寫(xiě)入標(biāo)題數(shù)據(jù)
Cell cell = titleRow.createCell(i);
cell.setCellValue(columnList.get(i));
}
//設(shè)置內(nèi)容行
if(dataList!=null && dataList.size()>0){
//序號(hào)是從1開(kāi)始的
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)建每行對(duì)應(yīng)的列,并賦值
for(int j = -1;j<dataList.get(0).size();j++){//由于多了一列序號(hào)列所以內(nèi)層循環(huán)從-1開(kāi)始
Cell cell = dataRow.createCell(j+1);
if(j==-1){//第一列是序號(hào)列,不是在數(shù)據(jù)庫(kù)中讀取的數(shù)據(jù),因此手動(dòng)遞增賦值
cell.setCellValue(count++);
}else{//其余列是數(shù)據(jù)列,將數(shù)據(jù)庫(kù)中讀取到的數(shù)據(jù)依次賦值
cell.setCellValue(dataList.get(i).get(j));
}
}
}
}
//將整理好的excel數(shù)據(jù)寫(xiě)入流中
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ù)制過(guò)來(lái)就能直接使用的,因此需要我們深究其原理,這樣可以應(yīng)對(duì)不同的場(chǎng)景寫(xiě)出屬于我們自己的合適的代碼,這里就不一一解釋了,代碼中注釋加的很清楚,有不懂的可以留言評(píng)論。
3.編寫(xiě)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)識(shí)")
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)建時(shí)間")
private Date createTime;
@ApiModelProperty(value = "項(xiàng)目編號(hào)")
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("序號(hào)","項(xiàng)目編碼", "項(xiàng)目名稱", "創(chuàng)建時(shí)間", "創(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("測(cè)試:{}",map);
testService.exportExcel(map.get("list"),response);
}
}4.測(cè)試
測(cè)試的話可以使用swagger或者postman,甚至你前端技術(shù)足夠ok的話也可以寫(xiě)個(gè)簡(jiǎn)單的頁(yè)面進(jìn)行測(cè)試,我是用的是swaager進(jìn)行的測(cè)試,下面就是我測(cè)試的結(jié)果了:



到此這篇關(guān)于spring boot 導(dǎo)出數(shù)據(jù)到excel的文章就介紹到這了,更多相關(guān)spring boot導(dǎo)出數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot死信隊(duì)列?DLX?配置和使用思路分析
死信隊(duì)列簡(jiǎn)稱就是DLX,死信交換機(jī)和死信隊(duì)列和普通的沒(méi)有區(qū)別,當(dāng)消息成為死信后,如果該隊(duì)列綁定了死信交換機(jī),則消息會(huì)被死信交換機(jī)重新路由到死信隊(duì)列,本文給大家介紹Springboot死信隊(duì)列?DLX的相關(guān)知識(shí),感興趣的朋友一起看看吧2022-03-03
Spring解決循環(huán)依賴問(wèn)題的四種方法匯總
這篇文章主要介紹了Spring解決循環(huán)依賴問(wèn)題的四種方法匯總,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-07-07
springboot與vue實(shí)現(xiàn)簡(jiǎn)單的CURD過(guò)程詳析
這篇文章主要介紹了springboot與vue實(shí)現(xiàn)簡(jiǎn)單的CURD過(guò)程詳析,圍繞springboot與vue的相關(guān)資料展開(kāi)實(shí)現(xiàn)CURD過(guò)程的過(guò)程介紹,需要的小伙伴可以參考一下2022-01-01
IDEA個(gè)性化設(shè)置注釋模板詳細(xì)講解版
IDEA自帶的注釋模板不是太好用,我本人到網(wǎng)上搜集了很多資料系統(tǒng)的整理了一下制作了一份比較完整的模板來(lái)分享給大家,下面這篇文章主要給大家介紹了IDEA個(gè)性化設(shè)置注釋模板的相關(guān)資料,需要的朋友可以參考下2024-01-01
Java優(yōu)先隊(duì)列(PriorityQueue)重寫(xiě)compare操作
這篇文章主要介紹了Java優(yōu)先隊(duì)列(PriorityQueue)重寫(xiě)compare操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
java中Class.getMethods()和Class.getDeclaredMethods()方法的區(qū)別
這篇文章主要介紹了java中Class.getMethods()和Class.getDeclaredMethods()方法的區(qū)別 ,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-09-09
詳解Java回調(diào)的原理與實(shí)現(xiàn)
回調(diào)函數(shù),顧名思義,用于回調(diào)的函數(shù)。回調(diào)函數(shù)只是一個(gè)功能片段,由用戶按照回調(diào)函數(shù)調(diào)用約定來(lái)實(shí)現(xiàn)的一個(gè)函數(shù)?;卣{(diào)函數(shù)是一個(gè)工作流的一部分,由工作流來(lái)決定函數(shù)的調(diào)用(回調(diào))時(shí)機(jī)。2017-03-03

