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()
相关推荐
李昊哲小课1 小时前
第1章-PySide6 基础认知与环境配置
python·pyqt·pyside
2401_894241922 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
Zzzz_my3 小时前
正则表达式(RE)
pytorch·python·正则表达式
天天鸭3 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
setmoon2144 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
2401_833197734 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python
敏编程5 小时前
一天一个Python库:tomlkit - 轻松解析和操作TOML配置
python
2401_879693875 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
yunyun321235 小时前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
团子和二花6 小时前
openclaw平替之nanobot源码解析(七):Gateway与多渠道集成
python·gateway·agent·智能体·openclaw·nanobot