如何處理大數(shù)據(jù)量的Excel導(dǎo)出功能?
在使用Spring Boot和MyBatis進(jìn)行報表導(dǎo)出功能開發(fā)時,處理大數(shù)據(jù)量的Excel文件(從幾十兆到幾個G)的導(dǎo)出是一個常見而又具有挑戰(zhàn)性的任務(wù)。本文將詳細(xì)介紹如何高效地處理大數(shù)據(jù)量的Excel導(dǎo)出,包括如何生成Excel文件并導(dǎo)出,同時通過接口向前端返回進(jìn)度信息。

1. 使用合適的Excel處理庫
對于大數(shù)據(jù)量的Excel文件,選擇合適的Excel處理庫至關(guān)重要。以下是一些推薦的庫:
- Apache POI:適用于較小數(shù)據(jù)量的Excel處理。
- SXSSF (Streaming Usermodel API):Apache POI提供的流式API,可以處理較大數(shù)據(jù)量。
- EasyExcel:阿里巴巴開源的Excel處理庫,內(nèi)存占用較小,適合處理大數(shù)據(jù)量。
在本文中,我們將使用EasyExcel來實(shí)現(xiàn)流式寫入功能。
2. 分頁查詢數(shù)據(jù)
對于大數(shù)據(jù)量的查詢,建議使用分頁查詢來減小單次查詢的數(shù)據(jù)量,從而減輕內(nèi)存壓力。在MyBatis的Mapper中實(shí)現(xiàn)分頁查詢的方法如下:
@Mapper
public interface DataMapper {
List<Data> selectData(@Param("offset") int offset, @Param("limit") int limit);
}3. 流式寫入Excel
使用EasyExcel進(jìn)行流式寫入,避免一次性將所有數(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. 異步處理
對于非常大的數(shù)據(jù)導(dǎo)出任務(wù),建議使用異步處理,并通過消息隊(duì)列或任務(wù)調(diào)度框架(如Quartz)來管理導(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) {
// 流式寫入邏輯
}
}在Spring Boot的主配置類中啟用異步支持:
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í)時進(jìn)度推送
為了在執(zhí)行大數(shù)據(jù)量的Excel導(dǎo)出時向前端返回進(jìn)度信息,我們可以使用WebSocket進(jìn)行實(shí)時通信。下面是具體的實(shí)現(xiàn)步驟:
添加WebSocket依賴
在pom.xml中添加WebSocket依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>配置WebSocket
創(chuàng)建一個WebSocket配置類:
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)建一個WebSocket處理器類:
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寫入器
// 設(shè)置分頁大小
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ì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");
});
}至此,通過以上步驟,可以使用Spring Boot和MyBatis實(shí)現(xiàn)高效的大數(shù)據(jù)量Excel導(dǎo)出功能,并通過WebSocket實(shí)時向前端推送進(jìn)度信息,從而提升用戶體驗(yàn)。如果對Redis或其他緩存技術(shù)更熟悉,也可以通過緩存存儲進(jìn)度信息并定期輪詢來實(shí)現(xiàn)類似的功能。希望本文對你有所幫助!
























