折腾:
【已解决】用openpyxl去新建excel文件并保存数据和设置单元格样式
期间,想要给单元格设置类似于:
的背景色。
且去网上找到了
170,207,145
的hex color的值是:
http://www.sioe.cn/yingyong/yanse-rgb-16/
#AACF91
找了下,貌似只有sheet的tab设置背景色?
openpyxl cell background color
python – Adding a background color to Cell OpenPyXL – Stack Overflow
Best way to set cell background colour in openpyxl
OpenPyXL – Fill Cells with Color:learnpython
但是本来要去设置绿色背景,怎么代码:
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Alignment
from openpyxl.styles import PatternFill
# create new output unified format excel file
wbOut = Workbook()
logging.info("wbOut=%s", wbOut)
wsStorybook = wbOut.create_sheet(StorybookSheetTitle)
wsSong = wbOut.create_sheet(SongSheetTitle)
logging.info("wsStorybook=%s, wsSong=%s", wsStorybook, wsSong)
# init headers
def initOutputExcelHeaders(ws):
commonBackgroundColor = "AACF91"
logging.info("ws=%s", ws)
nameCell = ws["A1"]
nameCell.value = "名称"
nameCell.alignment = Alignment(horizontal=’center’, vertical=’center’)
nameCell.fill = PatternFill(bgColor=commonBackgroundColor, fill_type="solid")
ws.merge_cells(‘A1:A2’)
initOutputExcelHeaders(wsStorybook)
initOutputExcelHeaders(wsSong)
wbOut.save(OutputUnifiedFormatExcelFilename)
出来的效果却是黑色:
openpyxl PatternFill cell
难道是:
此处的RGB的值不是这么算的?
170 -》 hex是:0XAA
207-〉hex:0xCF
145 -》 hex:0x91
没错啊。
找找是不是PatternFill打开方式有误
openpyxl PatternFill cell
openpyxl.styles.fills module — openpyxl 2.5.3 documentation
Working with styles — openpyxl 2.5.0 documentation
openpyxl.styles.PatternFill Python Example
Can’t set cell background colour – Google Groups
python操作xlsx文件的包openpyxl – CSDN博客
“fill1 = PatternFill(start_color = ‘FFFF00’, end_color = ‘FFFF00’, fill_type = ‘solid’) #设置单元格背景色”
去试试
注意到:
http://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.fills.html
“bgColor
Values must be of type <class ‘openpyxl.styles.colors.Color’>”
看来是:
缺少了Color(xxx)
去试试
commonBackgroundColorHex = "AACF91"
logging.info("ws=%s", ws)
nameCell = ws["A1"]
nameCell.value = "名称"
nameCell.alignment = Alignment(horizontal=’center’, vertical=’center’)
# nameCell.fill = PatternFill(bgColor=commonBackgroundColor, fill_type="solid")
# nameCell.fill = PatternFill(bgColor=Color(commonBackgroundColorHex), fill_type="solid")
nameCell.fill = PatternFill(bgColor=Color(commonBackgroundColorHex), fill_type="solid")
问题依旧。
nameCell.fill = PatternFill(bgColor=colors.GREEN, fill_type="solid")
结果:
问题依旧。
nameCell.fill = PatternFill(start_color=colors.GREEN, end_color=colors.GREEN, fill_type="solid")
结果:
是可以的:
去换成我之前的颜色:
nameCell.fill = PatternFill(start_color=commonBackgroundColorHex, end_color=commonBackgroundColorHex, fill_type="solid")
结果:
就对了:
【总结】
此处,想要用openpyxl设置背景色,用PatternFill的bgColor:
nameCell.fill = PatternFill(bgColor=Color("AACF91"), fill_type="solid")
结果却导致黑色背景
最后是换成:
nameCell.fill = PatternFill(start_color="AACF91", end_color="AACF91", fill_type="solid")
就可以了。
前面bgClor无法工作的根本的原因,暂时懒得深究了。
转载请注明:在路上 » 【已解决】openpyxl中给单元格设置背景色