使用StyleFrame从pandas到Excel:如何禁用环绕文本和收缩以适应?

2024-06-17 13:39:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用StyleFrame从pandas导出到Excel。在

默认情况下,单元格的格式为“换行文本”和“缩小以适合”。(如何)我可以更改这些设置?在

API documentation说明utils模块包含最广泛使用的元素样式值,并且只要Excel识别它,就可以直接使用utils模块中不存在的值。在

在这种情况下,我需要为Excel指定什么?如何/从何处了解Excel的期望?先谢谢你!在

我尝试过的例子:

此代码工作完美:

sf.apply_column_style(cols_to_style=['A'], styler_obj=Styler(bg_color=utils.colors.blue))

但我的问题是,我不知道要更改什么才能关闭文本环绕和缩小以适应选项:

^{pr2}$

Tags: 模块代码文本api元素pandasstyledocumentation
2条回答

坏消息是在当前版本中不能很好地完成它。在

好消息是,您现在可以对它进行monkey补丁,我将在下一个版本中为它公开一个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实例进行monkey-patch,但这需要更多的创造力:

^{pr2}$

从版本1.3开始,可以将wrap_text和{}直接传递给Styler,例如no_wrap_text_style = Styler(wrap_text=False)

相关问题 更多 >