使用StyleFrame从大pandas到Excel:如何禁用包装文本&缩小以适合?
我使用StyleFrame从pandas导出到Excel。
单元格格式化为“包装文本”和“缩小到适合”默认情况下。 (如何)可以更改这些设置?
API文档描述了utils模块包含最广泛使用的样式元素值,并且只要Excel能够识别,就可以直接使用utils模块中不存在的值。
在这种情况下,我需要为Excel指定什么? 我如何/在哪里可以找出Excel的期望? 提前谢谢了!
我曾经尝试过的例子:
此代码完美:
sf.apply_column_style(cols_to_style=['A'], styler_obj=Styler(bg_color=utils.colors.blue))
但我的问题是,我不知道要改变什么来closures文本环绕和缩小以适应选项:
sf.apply_column_style(cols_to_style=['A'], styler_obj=Styler(text_control=wrap_text.none)) NameError: name 'wrap_text' is not defined sf.apply_column_style(cols_to_style=['A'], styler_obj=Styler(text_control=utils.wrap_text.none)) AttributeError: module 'StyleFrame.utils' has no attribute 'wrap_text' sf.apply_column_style(cols_to_style=['A'], styler_obj=Styler(utils.wrap_text.none)) AttributeError: module 'StyleFrame.utils' has no attribute 'wrap_text' sf.apply_column_style(cols_to_style=['A'], styler_obj=Styler(wrap_text=False)) TypeError: __init__() got an unexpected keyword argument 'wrap_text'
坏消息是,在当前版本中你不能很好地做到这一点。
好消息是,你现在可以猴子补丁,我会在下一个版本中公开一个API。
from openpyxl.styles import (PatternFill, Style, Color, Border, Side, Font, Alignment, Protection) from StyleFrame import StyleFrame, Styler, utils def my_create_style(self): side = Side(border_style=self.border_type, color=utils.colors.black) border = Border(left=side, right=side, top=side, bottom=side) return Style(font=Font(name=self.font, size=self.font_size, color=Color(self.font_color), bold=self.bold, underline=self.underline), fill=PatternFill(patternType='solid', fgColor=self.bg_color), alignment=Alignment(horizontal='center', vertical='center', wrap_text=False, # use True/False as needed shrink_to_fit=False, # use True/False as needed indent=0), border=border, number_format=self.number_format, protection=Protection(locked=self.protection)) Styler.create_style = my_create_style # rest of code
请记住,这将改变所有Styler
对象的行为。 如果你想更好的控制,你可以猴子补丁个人Styler
实例,但它需要更多的创造力:
from functools import partial # ... and rest of imports from above example # same code as above a_style = Styler(bg_color=utils.colors.blue) # this needs to be done BEFORE applying a_style.create_style = partial(my_create_style, a_style) sf.apply_column_style(cols_to_style=['A'], styler_obj=a_style)