如何處理大數(shù)據(jù)量的Excel導(dǎo)出功能?
在使用Spring Boot和MyBatis進(jìn)行報(bào)表導(dǎo)出功能開(kāi)發(fā)時(shí),處理大數(shù)據(jù)量的Excel文件(從幾十兆到幾個(gè)G)的導(dǎo)出是一個(gè)常見(jiàn)而又具有挑戰(zhàn)性的任務(wù)。本文將詳細(xì)介紹如何高效地處理大數(shù)據(jù)量的Excel導(dǎo)出,包括如何生成Excel文件并導(dǎo)出,同時(shí)通過(guò)接口向前端返回進(jìn)度信息。
1. 使用合適的Excel處理庫(kù)
對(duì)于大數(shù)據(jù)量的Excel文件,選擇合適的Excel處理庫(kù)至關(guān)重要。以下是一些推薦的庫(kù):
- Apache POI:適用于較小數(shù)據(jù)量的Excel處理。
- SXSSF (Streaming Usermodel API):Apache POI提供的流式API,可以處理較大數(shù)據(jù)量。
- EasyExcel:阿里巴巴開(kāi)源的Excel處理庫(kù),內(nèi)存占用較小,適合處理大數(shù)據(jù)量。
在本文中,我們將使用EasyExcel來(lái)實(shí)現(xiàn)流式寫(xiě)入功能。
2. 分頁(yè)查詢(xún)數(shù)據(jù)
對(duì)于大數(shù)據(jù)量的查詢(xún),建議使用分頁(yè)查詢(xún)來(lái)減小單次查詢(xún)的數(shù)據(jù)量,從而減輕內(nèi)存壓力。在MyBatis的Mapper中實(shí)現(xiàn)分頁(yè)查詢(xún)的方法如下:
@Mapper
public interface DataMapper {
List<Data> selectData(@Param("offset") int offset, @Param("limit") int limit);
}
3. 流式寫(xiě)入Excel
使用EasyExcel進(jìn)行流式寫(xiě)入,避免一次性將所有數(shù)據(jù)加載到內(nèi)存中,具體實(shí)現(xiàn)如下:
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExportService {
@Autowired
private DataMapper dataMapper;
public void exportLargeData(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("大數(shù)據(jù)導(dǎo)出", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), Data.class);
ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet("Sheet1");
int pageSize = 1000;
int pageNum = 0;
List<Data> dataList;
while (true) {
dataList = dataMapper.selectData(pageNum * pageSize, pageSize);
if (dataList.isEmpty()) {
break;
}
sheetBuilder.doWrite(dataList);
pageNum++;
}
}
}
4. 異步處理
對(duì)于非常大的數(shù)據(jù)導(dǎo)出任務(wù),建議使用異步處理,并通過(guò)消息隊(duì)列或任務(wù)調(diào)度框架(如Quartz)來(lái)管理導(dǎo)出任務(wù)。使用Spring的@Async注解可以實(shí)現(xiàn)異步處理:
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class ExportService {
@Autowired
private DataMapper dataMapper;
@Async
public void exportLargeDataAsync(HttpServletResponse response) {
exportLargeData(response);
}
public void exportLargeData(HttpServletResponse response) {
// 流式寫(xiě)入邏輯
}
}
在Spring Boot的主配置類(lèi)中啟用異步支持:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5. 實(shí)時(shí)進(jìn)度推送
為了在執(zhí)行大數(shù)據(jù)量的Excel導(dǎo)出時(shí)向前端返回進(jìn)度信息,我們可以使用WebSocket進(jìn)行實(shí)時(shí)通信。下面是具體的實(shí)現(xiàn)步驟:
添加WebSocket依賴(lài)
在pom.xml中添加WebSocket依賴(lài):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置WebSocket
創(chuàng)建一個(gè)WebSocket配置類(lèi):
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ExportProgressHandler(), "/exportProgress").setAllowedOrigins("*");
}
}
創(chuàng)建WebSocket處理器
創(chuàng)建一個(gè)WebSocket處理器類(lèi):
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
public class ExportProgressHandler extends TextWebSocketHandler {
private static ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) {
sessions.put(session.getId(), session);
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
// 處理接收到的消息(如果需要)
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
sessions.remove(session.getId());
}
public static void sendProgress(String sessionId, String progress) throws IOException {
WebSocketSession session = sessions.get(sessionId);
if (session != null && session.isOpen()) {
session.sendMessage(new TextMessage(progress));
}
}
}
修改導(dǎo)出服務(wù)
在導(dǎo)出服務(wù)中推送進(jìn)度信息:
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
@Service
public class ExportService {
@Autowired
private DataMapper dataMapper;
@Async
public void exportLargeDataAsync(HttpServletResponse response, String sessionId) {
exportLargeData(response, sessionId);
}
public void exportLargeData(HttpServletResponse response, String sessionId) {
// 初始化Excel寫(xiě)入器
// 設(shè)置分頁(yè)大小
int pageSize = 1000;
int pageNum = 0;
List<Data> dataList;
while (true) {
dataList = dataMapper.selectData(pageNum * pageSize, pageSize);
if (dataList.isEmpty()) {
break;
}
sheetBuilder.doWrite(dataList);
// 計(jì)算進(jìn)度
int progress = (pageNum * pageSize * 100) / totalRows;
try {
ExportProgressHandler.sendProgress(sessionId, "Progress: " + progress + "%");
} catch (IOException e) {
e.printStackTrace();
}
pageNum++;
}
}
}
前端WebSocket接收進(jìn)度
在前端使用WebSocket接收進(jìn)度信息,例如在JavaScript中:
let socket = new WebSocket("ws://localhost:8080/exportProgress");
socket.onmessage = function(event) {
let progress = event.data;
console.log("Progress: " + progress);
// 更新前端進(jìn)度條或其他UI
};
function startExport() {
fetch("/export/start")
.then(response => response.json())
.then(data => {
console.log("Export started");
});
}
至此,通過(guò)以上步驟,可以使用Spring Boot和MyBatis實(shí)現(xiàn)高效的大數(shù)據(jù)量Excel導(dǎo)出功能,并通過(guò)WebSocket實(shí)時(shí)向前端推送進(jìn)度信息,從而提升用戶(hù)體驗(yàn)。如果對(duì)Redis或其他緩存技術(shù)更熟悉,也可以通過(guò)緩存存儲(chǔ)進(jìn)度信息并定期輪詢(xún)來(lái)實(shí)現(xiàn)類(lèi)似的功能。希望本文對(duì)你有所幫助!