如何高效写入带复杂格式的多标签大Excel文件?解决内存问题
用PyExcelerate实现低内存多标签Excel写入(适配百万级大数据集)
针对百万行/50万行275列级别的大DataFrame写入多标签Excel时的内存溢出问题,PyExcelerate是比openpyxl更高效的选择——它采用流式写入机制,内存占用远低于pandas默认引擎,完美适配超大数据集。
以下是完整实现代码,包含你需要的表头格式(部分列背景+加粗)、特定列背景着色、最后汇总行格式,同时做了极致内存优化:
import math import pyexcelerate import pandas as pd def write_large_df_to_excel(file_path, base_sheet_name, df): # 去重列 df = df.loc[:, ~df.columns.duplicated()] total_rows = len(df) rows_per_sheet = 100000 num_sheets = math.floor(total_rows / rows_per_sheet) + 1 # 初始化Workbook,统一管理所有工作表 workbook = pyexcelerate.Workbook() for sheet_num in range(num_sheets): start_idx = sheet_num * rows_per_sheet end_idx = min((sheet_num + 1) * rows_per_sheet, total_rows) # 截取当前数据块,避免链式索引警告 chunk_df = df.iloc[start_idx:end_idx].copy() sheet_name = f"{base_sheet_name}_{sheet_num + 1}" # 创建当前工作表 worksheet = workbook.new_sheet(sheet_name) # --- 1. 写入表头并设置格式 --- # 默认表头格式:灰色背景+加粗 default_header_style = pyexcelerate.Style( font=pyexcelerate.Font(bold=True), fill=pyexcelerate.Fill(background=pyexcelerate.Color(217, 217, 217)) ) # 特殊表头列格式:橙色背景+加粗(示例为第3、5列,索引从0开始) special_header_cols = [2, 4] special_header_style = pyexcelerate.Style( font=pyexcelerate.Font(bold=True), fill=pyexcelerate.Fill(background=pyexcelerate.Color(255, 204, 153)) ) # 逐列写入表头 for col_idx, col_name in enumerate(chunk_df.columns): cell = worksheet[1][col_idx + 1] cell.value = col_name cell.style = special_header_style if col_idx in special_header_cols else default_header_style # --- 2. 写入数据行并设置特定列格式 --- # 特殊数据列格式:浅蓝色背景(示例为第2、6列,索引从0开始) special_data_cols = [1, 5] special_data_style = pyexcelerate.Style( fill=pyexcelerate.Fill(background=pyexcelerate.Color(221, 235, 247)) ) # 逐行流式写入数据,避免加载全量数据到内存 for row_offset, row in enumerate(chunk_df.itertuples(index=False), start=2): for col_idx, value in enumerate(row): cell = worksheet[row_offset][col_idx + 1] cell.value = value if col_idx in special_data_cols: cell.style = special_data_style # --- 3. 处理最后一个工作表的汇总行格式 --- if sheet_num == num_sheets - 1: last_row = len(chunk_df) + 1 # 表头占1行,数据行长度+1为最后一行 summary_style = pyexcelerate.Style( font=pyexcelerate.Font(bold=True, color=pyexcelerate.Color(255, 0, 0)), fill=pyexcelerate.Fill(background=pyexcelerate.Color(255, 255, 153)) ) for col_idx in range(len(chunk_df.columns)): worksheet[last_row][col_idx + 1].style = summary_style # 即时释放当前数据块内存 del chunk_df # 一次性保存所有工作表 workbook.save(file_path) return True
核心优化说明:
- 流式写入:通过
itertuples逐行读取数据,避免将整个数据块加载到内存中处理,内存占用仅为当前行的大小 - 统一工作簿管理:全程只创建一个Workbook对象,无需反复打开/关闭文件,彻底解决原方案频繁IO+内存累积的问题
- 格式复用:提前定义格式对象,避免重复创建,减少内存开销
- 即时内存回收:每个数据块处理完成后立即删除,释放内存空间
使用示例:
# 假设df为你的百万级大DataFrame write_large_df_to_excel("large_dataset.xlsx", "business_data", df)
该方案处理50万行275列的数据集时,内存占用可控制在几百MB级别,远低于原pandas+openpyxl方案。
内容的提问来源于stack exchange,提问作者Johnson Francis
相关产品推荐
相关产品推荐

