我正在尝试使用pythons OPENPYXL模块在Excel电子表格上设置样式。我一直想出这个错误:
' STR'对象没有属性' BLACK'
基本上,我的代码从.xlsx文件中读取已知值列表,并将它们放入python列表中。我使用该列表来比较访问表中列中的值,以确保每个单元格中的值与已知值相比是正确的。
当我尝试使用openpyxl设置样式时,我的脚本爆炸了。出于某种原因,出现上述错误。奇怪的是,我甚至没有在任何地方使用BLACK,当我尝试设置填充时似乎出错了。在脚本的 SearchCursor 部分,它遍历每一行。第二遍就是剧本爆炸了。我有一种想要覆盖某些东西的感觉,但我无法弄清楚是什么。
import openpyxl, arcpy
from arcpy import env
from openpyxl import Workbook
env.workspace = r"Z:\Access_Tables\Access_Table.gdb"
TableList = []
for row in arcpy.SearchCursor(r"Z:\Domains\Domains.xlsx\DOMAINS$"):
TableList.append(row.Code)
# Create workbook for report. Openpyxl
workbook = openpyxl.Workbook()
ws = workbook.get_active_sheet()
ws.title = "Test"
workbook.remove_sheet(ws)
# List out the access tables in the workspace
for fc in arcpy.ListFeatureClasses():
# Processing SOIL Point access table
if fc == "SOIL":
# List the column headings from the access table to be applied to the .xlsx table
fieldnames = [f.name for f in arcpy.ListFields(fc)]
# Create Sheet. Openpyxl
new_sheet = workbook.create_sheet(None,fc)
dictFieldnames = {}
for num,fname in enumerate(fieldnames):
dictFieldnames[num] = fname
# Write to cell, openpyxl
new_sheet.cell(None,0,num).value = fname
col_let = openpyxl.cell.get_column_letter(num + 1)
new_sheet.column_dimensions[col_let].width = len(fname) + 3
# Process SOIL Field
if "SOIL" in fieldnames:
# Set a counter and Loop through each row of the access table
x = 1
for row in arcpy.SearchCursor(fc):
for key, value in dictFieldnames.iteritems():
if value == "SOIL":
fieldKey = key
if not row.SOIL or len(row.SOIL.strip()) == 0:
# Openpyxl write. Set fill and color for cell. Write the unique id to the cell.
new_sheet.cell(None,x,fieldKey).style.fill.fill_type = openpyxl.style.Fill.FILL_SOLID
new_sheet.cell(None,x,fieldKey).style.fill.start_color.index = openpyxl.style.Color = 'FF808000'
new_sheet.cell(None,x,fieldKey).value = row.OBJECTID
x += 1
print 'first'
elif len(row.INCLUSION_TYPE) not in range(2,5):
# Openpyxl write. Set fill and color for cell. Write the unique id to the cell.
new_sheet.cell(None,x,fieldKey).style.fill.fill_type = openpyxl.style.Fill.FILL_SOLID
new_sheet.cell(None,x,fieldKey).style.fill.start_color.index = openpyxl.style.Color = 'FF2F4F4F'
new_sheet.cell(None,x,fieldKey).value = row.OBJECTID
x += 1
print 'second'
elif row.SOIL.upper() not in [y.upper() for y in TableList]:
# Openpyxl write. Set fill and color for cell. Write the unique id to the cell.
new_sheet.cell(None,x,fieldKey).style.fill.fill_type = openpyxl.style.Fill.FILL_SOLID
new_sheet.cell(None,x,fieldKey).style.fill.start_color.index = openpyxl.style.Color = 'FF00FFFF'
new_sheet.cell(None,x,fieldKey).value = row.OBJECTID
x += 1
print 'third'
print x
答案 0 :(得分:2)
问题出在那里,你正在定义颜色。只需将颜色指定给style.fill.start_color.index
即可。例如:
new_sheet.cell(None,x,fieldKey).style.fill.start_color.index = 'FF808000'
而不是:
new_sheet.cell(None,x,fieldKey).style.fill.start_color.index = openpyxl.style.Color = 'FF808000'