如何迭代满足特定条件的单元格中的 sheet 和颜色?使用 Python 和 openpyxl
How do I iterate over my sheet and color in cells that meet a specific condition? Using Python and openpyxl
我想遍历 sheet 并在单元格不是 'empty'/null 时填充单元格
如果单元格为空则无需任何操作
如果单元格为 !empty,则将其着色(填充)为
错误信息是
sheet[i].fill = PatternFill(fill_type='solid', start_color='43e33b', end_color='43e33b')
AttributeError: 'tuple' object has no attribute 'fill'
我使用的代码是
import openpyxl as xl
from openpyxl.styles import Font, Fill, Color, colors, PatternFill
# creating a variable to take any filename input from user
filename = input('Enter filename here: ')
# loading workbook on local computer c drive using filename
wb = xl.load_workbook(f'c:\Users\Charlie\Desktop\{filename}.xlsx')
# working with sheet1 on wb 'workbook'
sheet = wb['Sheet1']
# defining pacing list function
def packing_list():
# deleting columns so that columns required are left for new file
sheet.delete_cols(1, 14)
max_rows = sheet.max_row
print(max_rows)
for i in range(1, max_rows):
if sheet.cell(column=7, row=i, value=""):
sheet[i].fill = PatternFill(fill_type='solid',
start_color='43e33b', end_color='43e33b')
else:
break
# saving new worksheet to desktop with name packing_list
wb.save('c:\Users\Charlie\Desktop\packing_list.xlsx')
sheet[i]
是一个包含第 i
行中所有单元格的元组,其中 i >= 1
sheet[i][j]
是第 i,j
个单元格,其中 j >= 0。因此第 7 列将是 sheet[i][6]
。
您可以使用 sheet.cell(column=7, row=i)
获得相同的结果,其中行和列都从 1 开始。
您应该可以毫无问题地设置sheet.cell(column=7, row=i).fill
我想遍历 sheet 并在单元格不是 'empty'/null 时填充单元格
如果单元格为空则无需任何操作
如果单元格为 !empty,则将其着色(填充)为
错误信息是
sheet[i].fill = PatternFill(fill_type='solid', start_color='43e33b', end_color='43e33b') AttributeError: 'tuple' object has no attribute 'fill'
我使用的代码是
import openpyxl as xl
from openpyxl.styles import Font, Fill, Color, colors, PatternFill
# creating a variable to take any filename input from user
filename = input('Enter filename here: ')
# loading workbook on local computer c drive using filename
wb = xl.load_workbook(f'c:\Users\Charlie\Desktop\{filename}.xlsx')
# working with sheet1 on wb 'workbook'
sheet = wb['Sheet1']
# defining pacing list function
def packing_list():
# deleting columns so that columns required are left for new file
sheet.delete_cols(1, 14)
max_rows = sheet.max_row
print(max_rows)
for i in range(1, max_rows):
if sheet.cell(column=7, row=i, value=""):
sheet[i].fill = PatternFill(fill_type='solid',
start_color='43e33b', end_color='43e33b')
else:
break
# saving new worksheet to desktop with name packing_list
wb.save('c:\Users\Charlie\Desktop\packing_list.xlsx')
sheet[i]
是一个包含第 i
行中所有单元格的元组,其中 i >= 1
sheet[i][j]
是第 i,j
个单元格,其中 j >= 0。因此第 7 列将是 sheet[i][6]
。
您可以使用 sheet.cell(column=7, row=i)
获得相同的结果,其中行和列都从 1 开始。
您应该可以毫无问题地设置sheet.cell(column=7, row=i).fill