问题描述
使用Python和openpyxl,我有一个进入工作簿的代码,每天向一些单元格中添加一堆信息,然后关闭并保存它.我的问题是,如果打开此工作簿,则代码将不起作用(显然).
Using Python and openpyxl I have a code that goes into a workbook, adds a bunch of information to some cells every day, and then closes and saves it. My problem is that if this workbook is open the code doesn't work (obviously).
通过使工作簿共享(多个用户可以一次编辑),我可以解决此问题,但是在代码运行一次之后,python保存,然后将其恢复为封闭的,未共享的工作簿.有人知道openpyxl是否可以另存为共享文件吗?我在网上找不到任何东西.先发制人的感谢您的帮助.
By making the workbook shared(multiple users can edit at once) I can overcome this problem, however after the code runs once, python saves and then reverts it back to a closed, unshared workbook.Anyone know if openpyxl can save as shared? I'm not finding anything online.Pre-emptive thanks for your help.
推荐答案
似乎openpyxl保存Excel工作簿时,内部的docProps/app.xml文件将被擦除并且仅包含最少的信息.
It seems that when openpyxl saves an Excel workbook, the docProps/app.xml file inside is wiped and contains only minimal information.
一种快速(又肮脏)的解决方案是使用zipfile获取这些信息并将其传输到新的/保存的文件中.
A quick (and dirty) solution is to use zipfile to get these information and transfer them into the new/saved file.
import zipfile, openpyxl
def shared_pyxl_save(file_path, workbook):
"""
`file_path`: path to the shared file you want to save
`workbook`: the object returned by openpyxl.load_workbook()
"""
zin = zipfile.ZipFile(file_path, 'r')
buffers = []
for item in zin.infolist():
buffers.append((item, zin.read(item.filename)))
zin.close()
workbook.save(file_path)
zout = zipfile.ZipFile(file_path, 'w')
for item, buffer in buffers:
zout.writestr(item, buffer)
zout.close()
这篇关于Python和openpyxl将我的共享工作簿保存为未共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!