spring?boot?導(dǎo)出數(shù)據(jù)到excel的操作步驟(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與vue實現(xiàn)簡單的CURD過程詳析
這篇文章主要介紹了springboot與vue實現(xiàn)簡單的CURD過程詳析,圍繞springboot與vue的相關(guān)資料展開實現(xiàn)CURD過程的過程介紹,需要的小伙伴可以參考一下2022-01-01
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ū)別 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09

