尝试使用Openpyxl格式化时,For循环会跳过某些单元格

时间:2018-10-18 20:40:32

标签: python for-loop openpyxl

所以我有这段代码可以清理一个Excel文件,并且一切正常,但是有些奇怪的事情发生了,我的某些单元格没有随机更新样式。我将代码中定义的10-12列设置为date_style,但有时工作表中的单元格未更新。这是代码:

from datetime import datetime
from openpyxl.styles import NamedStyle
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
import openpyxl, os

wb = openpyxl.load_workbook('Opportunities.xlsx', data_only=True)
sheet = wb['OpportunityList']
date_style = NamedStyle(name='datetime', number_format='MM/DD/YYYY')
bold = Font(bold=True)
no_fill = PatternFill(fill_type=None)

print('Deleting row ' + str(sheet.max_row))
sheet.delete_rows(sheet.max_row)

#Loop through the rows and update/delete as needed
for rowNum in range(sheet.max_row, 1, -1):  #start with the last row
    sheet.cell(row = rowNum, column = 10).value = datetime.strptime\
    (sheet.cell(row = rowNum, column = 10).value, '%m/%d/%Y').date()
    sheet.cell(row = rowNum, column = 11).value = datetime.strptime\
    (sheet.cell(row = rowNum, column = 11).value, '%m/%d/%Y').date()
    sheet.cell(row = rowNum, column = 12).value = datetime.strptime\
    (sheet.cell(row = rowNum, column = 12).value, '%m/%d/%Y').date()

    sheet.cell(row = rowNum, column = 10).style = date_style
    sheet.cell(row = rowNum, column = 11).style = date_style
    sheet.cell(row = rowNum, column = 12).style = date_style

    if sheet.cell(row = rowNum, column = 10).value <=\
    datetime.strptime('7/31/2017', "%m/%d/%Y").date():
        print('Deleting row ' + str(rowNum))
        sheet.delete_rows(rowNum)
    if sheet.cell(row = rowNum, column = 4).value ==\
    'Open' and sheet.cell(row = rowNum, column = 11).value <=\
    datetime.strptime('12/31/2016', "%m/%d/%Y").date():
        print('Deleting row ' + str(rowNum))
        sheet.delete_rows(rowNum)
    if sheet.cell(row = rowNum, column = 10).value <\
    sheet.cell(row = rowNum, column = 11).value:
        sheet.cell(row = rowNum, column = 11).value =\
        sheet.cell(row = rowNum, column = 10).value

for rowNum in sheet['1:1']:
    rowNum.font = bold
    rowNum.fill = no_fill

for col in sheet.columns:
     column = col[0].column # Get the column name
     sheet.column_dimensions[column].width = 20

wb.save('Updated_Opportunities.xlsx')

查看屏幕截图以了解我在说什么:

enter image description here

如您所见,某些单元格保留默认的'yyyy-mm-dd'样式,我不知道为什么。所有这三列最初都是文本列,因此for循环肯定会将它们更新为日期类型,只是格式部分有时会失败。 3列中的几乎所有单元格都会更新,但是有一些异常值,我对此没有解释。没什么大不了的,但是我是一个初学者,所以也许我在不知道的情况下在for循环中做错了事。

预先感谢

0 个答案:

没有答案