当前位置:网站首页>【openpyxl】只读模式、只写模式
【openpyxl】只读模式、只写模式
2022-08-10 23:50:00 【冰冷的希望】
1.说明
前面我们使用的normal模式进行读写Excel文件,这是一种兼顾读写相对比较平衡的模式,但是,数据加载到内存占用的资源是比较大的,大概是文件的50倍,如果你的Excel文件本身就10M,加载之后程序
需要占用0.5G内存,这很不划算(大内存电脑请自动忽略),所以我们需要考虑是不是可以选择只读或只写模式以便提高性能
2.只读模式
只读模式,如果你需要读取很大的Excel文件,但是又不改变和保存,例如只读取数值用于其他数据分析,这时候我们完全可以使用只读模式提供性能
from openpyxl import load_workbook
# 加载Excel文件时使用read_only指定只读模式
wb = load_workbook(filename='large_file.xlsx', read_only=True)
ws = wb['big_data']
# 可以正常读取值
for row in ws.rows:
for cell in row:
print(cell.value)
# 注意:读取完之后需要手动关闭避免内存泄露
wb.close()
load_workbook参数说明:
定义:
def load_workbook(filename, read_only=False, keep_vba=KEEP_VBA, data_only=False, keep_links=True)
参数:
read_only:是否只读,默认False
keep_vba:是否使用VBA编程,默认False
data_only:是否只加载数据值,即丢弃公式、排序等操作,默认False
keep_links:是否保留超链接,默认True
3.只写模式
如果文件是以写为主,可以在创建工作簿的时候指定为只写模式以便提高性能,不管文件有多大,都可以把内存保持在10M以下
from openpyxl import Workbook
from openpyxl.cell import WriteOnlyCell
from openpyxl.comments import Comment
from openpyxl.styles import Font
wb = Workbook(write_only=True) # 创建工作簿时指定只写模式
ws = wb.create_sheet() # 需要通过create_sheet创建一个sheet
# 可以正常保存数据
for _ in range(100):
ws.append([i for i in range(200)]) # 只能通过append写
# 如果需要保留公式、注释等操作,可以使用WriteOnlyCell
cell = WriteOnlyCell(ws, value="冰冷的希望")
cell.font = Font(name='黑体', size=15)
cell.comment = Comment(text="这是注释", author="pan")
ws.append([cell])
wb.save('openpyxl/test.xlsx')
只写模式注意点:
1.需要通过create_sheet()创建表
2.只能通过append()增加数据,不能通过cell或iter_rows()
3.wb.save()之后不能再修改,否则抛出WorkbookAlreadySaved异常
边栏推荐
猜你喜欢
C language, operators of shift operators (> >, < <) explanation
【C语言】猜数字游戏的实现
学习Apache ShardingSphere解析器源码(一)
Why do programming languages have the concept of variable types?
SQL注入基础
高校就业管理系统设计与实现
How to recover deleted files from the recycle bin, two methods of recovering files from the recycle bin
Based on the SSM to reach the phone sales mall system
[C language] Implementation of guessing number game
只会懒汉式和饿汉式 你还不懂单例模式!
随机推荐
Mysql.慢Sql
22年全国程序员1月薪资出炉,才知道年薪 40 万以上的有这么多?
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 2 DGHJKL Problem Solution
CF1286E-Fedya the Potter Strikes Back【KMP,RMQ】
[Excel知识技能] 将“假“日期转为“真“日期格式
App regression testing, what are the efficient testing methods?
How to quickly grasp industry opportunities and introduce new ones more efficiently is an important proposition
Three-column layout implementation
9. Rest 风格请求处理
SQL注入基础
Is there a way out in the testing industry if it is purely business testing?
Software Testing Certificate (1) - Software Evaluator
【C语言】二分查找(折半查找)
缓存知识总结
图片懒加载(纯手写)
镜头之滤光片---关于日夜两用双通滤光片
开启新征程——枫叶先生第一篇博客
iNFTnews | In the Web3 era, users will have data autonomy
NOR FLASH闪存芯片ID应用之软件保护场景
李彦宏拆墙交朋友,大厂“塑料友情”能否帮百度啃下硬骨头?