Python 基于 xlsxwriter 实现百万数据导出 excel

追加导出 + 自动切换 sheet

⚠️ excel 中的每个 sheet 最多只能保存 1048576 行数据

python 复制代码
# 获取项目的根路径 rootPath
curPath = os.path.abspath(os.path.dirname(__file__))  
rootPath = curPath[:curPath.find(你的项目名称 + "/") + len(  
你的项目名称 + "/")]
# 临时文件
local_file_path = os.path.join(rootPath, "temp.xlsx")  
# 检查并删除现有的临时文件  
if os.path.exists(local_file_path):  
    os.remove(local_file_path)
    
sheet_number = 1  
sheet_name_format = "Sheet_{}"

# 数据量大,导出的数据又包含url的话,会疯狂报警告,大家用不到可以删掉
workbook = xlsxwriter.Workbook(local_file_path, options={'strings_to_urls': False})
table = workbook.add_worksheet(sheet_name_format.format(sheet_number))

# sheet 数据总条数
page_total = 0  
# 要写的行
row_number = 1
# 分批导出,每次 100000 条数据
default_limit = 100000
# 分批导出,第 1 页开始
page_number = 1

while True:
	# 分批获取数据
	data_list = get_data_list(page_number, default_limit) # 你的数据
	if len(data_list) == 0:  
		break  
	# sheet总条数,0代表第一次写入数据
	if page_total == 0:  
		# 标题
		header = [你的标题]
		table.write_row(0, 0, header)
		# todo 因为我把每个 sheet 控制在了 100万条,就切换下一个 sheet 了。 
		# todo 如果各位要是玩极限别忘了这里 page_total + 1
	  
	for item in data_list:  
		table.write_row(row_number, 0, list(item.values()))  
		row_number = row_number + 1 
	  
	page_total = page_total + len(data_list)  
	# 自动切换sheet
	if page_total >= 1000000:  
		# 换下一个sheet   
		sheet_number = sheet_number + 1  
		table = workbook.add_worksheet(sheet_name_format.format(sheet_number))  
		# 初始化
		page_total = 0  
		row_number = 1
	page_number = page_number + 1
# 关闭  
workbook.close()
相关推荐
jufeng13072 分钟前
【系列:TDengine 工业物联网实战:从零搭起可运行系统 · 第 4 篇】
python·时序数据库·tdengine·asyncio
努力搬砖的咸鱼6 分钟前
意图理解:让Agent从需求描述自动生成Pytest测试策略
人工智能·python·ai·单元测试·pytest·agent
2601_9563198819 分钟前
2026年下半年,量化学习要把交易认知和技术实现接起来
人工智能·python
EW Frontier26 分钟前
【雷达信号处理】5 个阵元追平 16 个阵元:稀疏阵列 STAP 的实测报告【附python+matlab代码】
python·matlab·信号处理·雷达·mimo·稀疏阵列·stap
卷无止境1 小时前
FastAPI的测试事件在测什么?
后端·python·fastapi
selfsongs1 小时前
Python学习之——multiprocessing 多进程编程
python
卷无止境1 小时前
FastAPI CLI 你需要认识这把命令行利器
后端·python·fastapi
云泽8081 小时前
Python 开发环境搭建全指南:从 Python 安装到 PyCharm 配置详解
开发语言·python·pycharm
IT小白杨1 小时前
海外业务账号安全保障:主流浏览器产品底层机制对比
数据库·python·安全·自动化·安全架构·指纹浏览器
ZC跨境爬虫1 小时前
LeetCode 119. 杨辉三角 II(原地更新优化详解 + Java Python 实现)
java·python·leetcode