Python and openpyxl is saving my shared workbook as unshared

谁都会走 提交于 2020-01-02 20:45:38

问题


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).

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.


回答1:


It seems that when openpyxl saves an Excel workbook, the docProps/app.xml file inside is wiped and contains only minimal information.

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()


来源:https://stackoverflow.com/questions/57363072/python-and-openpyxl-is-saving-my-shared-workbook-as-unshared

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!