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()
相关推荐
bing_1583 小时前
Excel 如何进行多条件查找或求和?
excel
秀儿还能再秀3 小时前
基于Excel的数据分析思维与分析方法
数据分析·excel
bing_1583 小时前
Excel 如何处理更复杂的嵌套逻辑判断?
excel
weixin_472339463 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
灵犀学长3 小时前
EasyExcel之SheetWriteHandler:解锁Excel写入的高阶玩法
spring boot·excel
烛阴8 小时前
简单入门Python装饰器
前端·python
好开心啊没烦恼8 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开8 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
2301_805054569 小时前
Python训练营打卡Day59(2025.7.3)
开发语言·python
万千思绪10 小时前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm