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()
相关推荐
程序员哈基耄8 分钟前
安全高效,本地运行:全能文件格式转换工具
大数据·python·安全
lixin55655644 分钟前
基于神经网络的音乐生成增强器
java·人工智能·pytorch·python·深度学习·语言模型
养海绵宝宝的小蜗44 分钟前
Python第二次作业
开发语言·python
我的xiaodoujiao1 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 43--添加allure测试报告显示信息和其他封装方法
python·学习·测试工具·allure
无垠的广袤1 小时前
【CPKCOR-RA8D1】RUHMI 转换 AI 模型
人工智能·python·嵌入式硬件·开发板
aiguangyuan1 小时前
从词袋到TF-IDF:sklearn文本特征工程实战指南
人工智能·python·nlp
数据知道1 小时前
PostgreSQL 实战:详解 UPSERT(INSERT ON CONFLICT)
数据库·python·postgresql
June bug1 小时前
(#数组/链表操作)寻找两个正序数组的中位数
数据结构·python·算法·leetcode·面试·职场和发展·跳槽
李昊哲小课1 小时前
奶茶店销售额预测模型
python·机器学习·线性回归·scikit-learn
电商API&Tina1 小时前
电商API接口的应用与简要分析||taobao|jd|微店
大数据·python·数据分析·json