將多個實體類集合寫入同一個 Excel 檔案的不同 Sheet 頁

slan_wyf發表於2024-07-28
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelUtil {
    /**
     * 將多個實體類集合寫入同一個 Excel 檔案的不同 Sheet 頁
     *
     * @param dataMap        實體類集合對映,鍵為 Sheet 索引,值為對應的實體類集合
     * @param outputFilePath 輸出 Excel 檔案路徑
     * @param excelName      Excel 檔名
     * @param sheetNames     Sheet 名稱對映,鍵為 Sheet 索引,值為對應的 Sheet 名稱
     */
    public static void writeDataToExcel(Map<Integer, List<?>> dataMap, String outputFilePath, String excelName, Map<Integer, String> sheetNames) {
        try (ExcelWriter excelWriter = EasyExcel.write(outputFilePath + "\\" + excelName).excelType(ExcelTypeEnum.XLSX).build()) {
            for (Map.Entry<Integer, List<?>> entry : dataMap.entrySet()) {
                int sheetIndex = entry.getKey();
                List<?> data = entry.getValue();
                String sheetName = sheetNames.get(sheetIndex);
                WriteSheet writeSheet = EasyExcel.writerSheet(sheetIndex, sheetName).head(data.get(0).getClass()).build();
                BatchUtil.execute(data, 1000, batchData -> excelWriter.write(batchData, writeSheet));
            }
        } catch (Exception e) {
            log.error("writeDataToExcel error: ", e);
        }
    }
}

相關文章