如何使用Python编辑几个excel工作簿中的单元格?

时间:2018-02-22 11:00:57

标签: python openpyxl

所以我在几个不同的文件夹中有相同的excel工作簿,即对于每个酒店我有一个文件,在该文件中有一个excel工作簿。现在,我需要进入每个文件并将工作表“设置”中单元格'B2'的内容更改为酒店名称(在我的代码中称为hotelname)。我尝试运行下面的代码,但它给我错误“C:\ Python34 \ python-3.4.4.amd64 \ lib \ site-packages \ openpyxl \ reader \ worksheet.py:319:UserWarning:Data Validation extension not not not not支持并将被删除“并且它不会改变我的Excel文件中的任何内容?

from openpyxl import load_workbook

log = 'G:\Data\Hotels\hotelnames.txt'  ##text file with a list of the hotel names 
file = open(log, 'r')
hotelnames = []
line = file.readlines()
for a in line:
    hotelnames.append(a.rstrip('\n'))

for hotel in hotelnames:
    wb = load_workbook("G:\\Data\\Hotels\\"+hotel+"\\"+hotel+" - Meetings\\"+hotel+"_Action_Log.xlsx", data_only = True)
    ws = wb["Set Up"]
    ws['B2'] = hotel  ### I want this cell to to have that particular hotel name
    wb.save

1 个答案:

答案 0 :(得分:0)

您的代码应调用方法wb.save,而不仅仅是引用它。通过添加一些括号并传递文件名以将文件保存到:

来做到这一点
wb.save(filename)

wb.save仅引用save方法,但不会调用它。

通过直接遍历文件对象,可以大大简化输入文件的处理:

import os.path

with open(log) as f:
    file_spec = os.path.join(r"G:\Data\Hotels", '{0}', '{0} - Meetings', '{0}_Action_Log.xlsx'
    for hotel in f:
        hotel = hotel.rstrip('\n')    # probably hotel.rstrip() is sufficient
        wb = load_workbook(file_spec.format(hotel), data_only = True)
        ws = wb["Set Up"]
        ws['B2'] = hotel
        wb.save(file_spec.format(hotel))    # careful, this overwrites the original file, it would be safer to save it to a new file.