Openpyxl不会以只读模式关闭Excel工作簿 [英] Openpyxl does not close Excel workbook in read only mode

查看:766
本文介绍了Openpyxl不会以只读模式关闭Excel工作簿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够用Python读取Excel文件,在读取完成后保持Python脚本运行,并在其他过程中编辑Excel文件.我正在使用python 2.7和openpyxl.

当前看起来像:

from openpyxl import load_workbook

def get_excel_data():
    OESwb = load_workbook(filename = OESconfigFile, data_only=True, 
                          read_only=True)
    ws = OESwb.get_sheet_by_name('MC01')
    aValue = ws['A1'].value
    return aValue

val = get_excel_data()

运行该函数后,即使我不想在Python中读取它,Excel文件仍然被锁定以供其他进程访问(它给出错误当前正在使用''文件名'.请稍后重试".)不再.

如何从脚本中关闭文件?我已经尝试了OESwb.close(),但是它给出了错误"Workbook对象没有属性close".我发现了这篇文章,但似乎没有帮助.

看来OESwb.save('filename.xlsx')是有效的,但前提是read_only = False.但是,理想的是能够关闭文件并仍然处于只读模式.看来这是openpyxl的错误,因为它应该在load_workbook完成后关闭文件.

解决方案

wb._archive.close()

也可以与use_iterator一起使用.

I want to be able to read an Excel file in Python, keep the Python script running doing something else after the reading is finished, and be able to edit the Excel file in another process in the meantime. I'm using python 2.7 and openpyxl.

Currently it looks like:

from openpyxl import load_workbook

def get_excel_data():
    OESwb = load_workbook(filename = OESconfigFile, data_only=True, 
                          read_only=True)
    ws = OESwb.get_sheet_by_name('MC01')
    aValue = ws['A1'].value
    return aValue

val = get_excel_data()

After I run the function, the Excel file is still locked for access from other processes (it gives the error "'filename' is currently in use. Try again later") even when I do not want to read it in Python anymore.

How can I close the file from my script? I've tried OESwb.close() but it gives the error "'Workbook' object has no attribute 'close'". I found this post but it doesn't seem to be helping.

EDIT: It appears OESwb.save('filename.xlsx') works, but only if read_only=False. However, it would be ideal to be able to close the file and still be in readonly mode. It appears this is a bug with openpyxl since it should close the file after load_workbook is finished.

解决方案

wb._archive.close()

Works with use_iterator too.

这篇关于Openpyxl不会以只读模式关闭Excel工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆