Alter the style of all cells with openpyxl

可紊 提交于 2020-02-27 23:26:25

问题


I'm using openpyxl 2.0.3 with python2.7.

Is there a way to apply a style to every cell in a worksheet? Lets say I want to change the font of all cells, similar to how I would open an excel document, hit ctrl+a, right click and change the format.


回答1:


There is no method to do this. At the moment the best approach would probably be to set the style for all the relevant columns or rows

style = Style(…)
for col in 'ABCD':
     ws._styles['A'] = style

I think we'll be working on improving handling styles in coming releases.




回答2:


I understand this question is effectively changing the default sheet (workbook?) font. This is essentially the same as my need to change the default font to match the other excel documents. There are many similar questions about changing font on a cell or column basis:

  1. 2011-07-21 - Use openpyxl to edit a Excel2007 file (.xlsx) without changing its own styles?
  2. 2011-12-09 - Setting styles in Openpyxl
  3. 2014-05-23 - Alter the style of all cells with openpyxl
  4. 2017-04-20 - Formatting Fonts and Alignment
  5. 2018-03-07 - How to change font size in Python OpenPyXL
  6. 2018-05-04 - Python Setting Style and Font Size in Excel

This hack is change the default workbook font. Clearly this is not supported by the API but I am happy to override the package. I started by searching for Calibri, a font I don't use on my computer:

Two lines in ..\openpyxl\styles\__init__.py look relevant:

from .fonts import Font, DEFAULT_FONT
from .named_styles import NamedStyle

Change in fonts.py:

# Hack default font
# DEFAULT_FONT = Font(name="Calibri", sz=11, family=2, b=False, i=False,
DEFAULT_FONT = Font(name="Calibri", sz=10, family=2, b=False, i=False,
                    color=Color(theme=1), scheme="minor")

Other places which appear to be worth looking are: named_styles.py, stylesheet.py, styleable.py, theme.py and workbook.py.

I'd appreciate any advice to tidy up changing the constant in fonts.py called from __init__.py.



来源:https://stackoverflow.com/questions/23830938/alter-the-style-of-all-cells-with-openpyxl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!