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()
相关推荐
Kusunoki_D1 小时前
PyTorch 环境配置
人工智能·pytorch·python
知秋丶2 小时前
大模型应用发展与Agent前沿技术趋势(下)
人工智能·python·ai agent
HenryLin3 小时前
美股量化分析系统 - 模块调用流程文档
python
跟橙姐学代码3 小时前
一文读懂 Python 的 JSON 模块:从零到高手的进阶之路
前端·python
躺不平的小刘4 小时前
从YOLOv5到RKNN:零冲突转换YOLOv5模型至RK3588 NPU全指南
linux·python·嵌入式硬件·yolo·conda·pyqt·pip
文火冰糖的硅基工坊4 小时前
[激光原理与应用-317]:光学设计 - Solidworks - 草图
开发语言·python·信息可视化·系统架构
高级测试工程师欧阳5 小时前
python中selenium怎么使用
python·pandas
BertieHuang5 小时前
(一)深入源码,从 0 到 1 实现 Cursor
人工智能·python·程序员
以泪为证5 小时前
WebSocket 任务分发系统代码深度分析与应用
python
jumin18065 小时前
python采用jdbc连接kerberos认证的hive
python·apache hive