目录

前言

继续搞Python对Excel文件的处理,这次主要解决如何使用Openpyxl模块的Styles来生成一个具有个性化样式的Excel文件。本篇基本算是翻译了部分实用的官方文档内容,推荐小伙伴们最好的学习方法,莫过于阅读官方文档。: )

官当文档传送门:http://openpyxl.readthedocs.org/en/default/styles.html#worksheet-additional-properties

系统软件

  • 系统

    • Windows 8.1
  • 软件
    • Python 3.4.3
    • IPython 4.0.0

Working with styles

使用Excel样式函数

Introduction(简介)

Styles are used to change the look of your data while displayed on screen. They are also used to determine the number format being used for a given cell or range of cells.

Styles是用于改变你的希望显示的数据的样式。也可以用于设置指定的单元格或单元区域的数字格式。

Styles can be applied to the following aspects

  • font to set font size, color, underlining, etc.(能够设定字体的大小、颜色、下划线等属性)
  • fill to set a pattern or color gradient(能够设置单元格的填充样式或颜色渐变)
  • border to set borders on a cell(能够设置单元格的边框)
  • cell alignment(能够设置单元格的对齐)
  • protection(能够设置访问限制)

Styles模块

The following are the default values(下面是函数的参数缺省值)

>>> from openpyxl.styles import PatternFill,Border,Side,Alignment,Protection,Font

>>> font = Font(name='Calibri',
... size=11,
... bold=False,
... italic=False,
... vertAlign=None,
... underline='none',
... strike=False,
... color='FF000000')
>>> fill = PatternFill(fill_type=None,
... start_color='FFFFFFFF',
... end_color='FF000000')
>>> border = Border(left=Side(border_style=None,
... color='FF000000'),
... right=Side(border_style=None,
... color='FF000000'),
... top=Side(border_style=None,
... color='FF000000'),
... bottom=Side(border_style=None,
... color='FF000000'),
... diagonal=Side(border_style=None,
... color='FF000000'),
... diagonal_direction=0,
... outline=Side(border_style=None,
... color='FF000000'),
... vertical=Side(border_style=None,
... color='FF000000'),
... horizontal=Side(border_style=None,
... color='FF000000')
... )
>>> alignment=Alignment(horizontal='general',
... vertical='bottom',
... text_rotation=0,
... wrap_text=False,
... shrink_to_fit=False,
... indent=0)
>>> number_format = 'General'
>>> protection = Protection(locked=True,
... hidden=False)
>>>

注意

Styles are shared between objects and once they have been assigned they cannot be changed. This stops unwanted side-effects such as changing the style for lots of cells when instead of only one.

不同的对象之间是可以共享同一个Styles的,并且一旦为对象指定了Styles之后就不可以再次更改。这是为了在更改很多的单元格的Styles而不仅只是更改一个单元格时能够避免不必要的副作用。

>>> from openpyxl.styles import colors
>>> from openpyxl.styles import Font, Color
>>> from openpyxl.styles import colors
>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> ws = wb.active
>>>
>>> a1 = ws['A1']
>>> d4 = ws['D4']
>>> ft = Font(color=colors.RED) #定义一个可以共享的Styles
>>> a1.font = ft
>>> d4.font = ft
>>>
>>> a1.font.italic = True # is not allowed 对象在指定Styles后是不允许被更改的
>>>
>>> # If you want to change the color of a Font, you need to reassign it::
>>> # 如果你想更改个别对象的Styles需要重新定义,且只会影响到个别对象
>>> a1.font = Font(color=colors.RED, italic=True) # the change only affects A1

Copying styles

Styles can also be copied(Styles可以被复制)

>>> from openpyxl.styles import Font
>>>
>>> ft1 = Font(name='Arial', size=14)
>>> ft2 = ft1.copy(name="Tahoma") #复制并修改特定属性
>>> ft1.name
'Arial'
>>> ft2.name
'Tahoma'
>>> ft2.size # copied from the 14.0

Basic Font Colors

Colors are usually RGB or aRGB hexvalues. The colors module contains some constants

Colors通常是RGB或者是RGB的十六进制表示。Colors模块包含了一些常量

>>> from openpyxl.styles import Font
>>> from openpyxl.styles.colors import RED
>>> font = Font(color=RED) #RGB
>>> font = Font(color="FFBB00") #RGB hexvalues

There is also support for legacy indexed colors as well as themes and tints

Colors也支持索引颜色、主题和色彩

>>> from openpyxl.styles.colors import Color
>>> c = Color(indexed=32) #legacy indexed colors 定制好的Color通过索引调用
>>> c = Color(theme=6, tint=0.5)

Applying Styles

Styles are applied directly to cells

Styles直接应用于单元格

>>> from openpyxl.workbook import Workbook
>>> from openpyxl.styles import Font, Fill
>>> wb = Workbook()
>>> ws = wb.active
>>> c = ws['A1'] #获取单元格对象
>>> c.font = Font(size=12) #直接修改单元格对象的字体样式

Styles can also applied to columns and rows but note that this applies only to cells created (in Excel) after the file is closed. If you want to apply styles to entire rows and columns then you must apply the style to each cell yourself. This is a restriction of the file format

Styles也可以应用于列和行,但是需要注意的是这种应用只能适用于在关闭文件之后创建的单元格。如果你想应用Style于全部的行和列,你必须为每一个单元格都应用Style。这是由于文件格式的制约

>>> col = ws.column_dimensions['A']    #获取A列的样式
>>> col.font = Font(bold=True)
>>> row = ws.row_dimensions[1] #获取1行的样式
>>> row.font = Font(underline="single")

Edit Page Setup

>>> from openpyxl.workbook import Workbook
>>>
>>> wb = Workbook()
>>> ws = wb.active
>>> #设置页面的样式
>>> ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
>>> ws.page_setup.paperSize = ws.PAPERSIZE_TABLOID
>>> ws.page_setup.fitToHeight = 0
>>> ws.page_setup.fitToWidth = 1

Edit Print Options

>>> from openpyxl.workbook import Workbook
>>>
>>> wb = Workbook()
>>> ws = wb.active
>>>
>>> ws.print_options.horizontalCentered = True #水平居中
>>> ws.print_options.verticalCentered = True #垂直居中

Header / Footer

Headers and footers use their own formatting language. This is fully supported when writing them.but, due to the complexity and the possibility of nesting, only partially when reading them.

头部和尾部使用它们自身的格式化语言。当你写的时候是完全支持的。但是由于复制性和嵌套的可能性,让你读取的时候可能只能读取到一个部分。

>>> from openpyxl.workbook import Workbook
>>>
>>> wb = Workbook()
>>> ws = wb.worksheets[0]
>>> #设置文件头部和页尾的样式
>>> ws.header_footer.center_header.text = 'My Excel Page'
>>> ws.header_footer.center_header.font_size = 14
>>> ws.header_footer.center_header.font_name = "Tahoma,Bold"
>>> ws.header_footer.center_header.font_color = "CC3366"

Python Module_openpyxl_styles 样式处理的更多相关文章

  1. PEP 8 - Python代码样式指南

    PEP 8 - Python代码样式指南 PEP: 8 标题: Python代码风格指南 作者: Guido van Rossum <python.org上的guido>,Barry Wa ...

  2. pycharm python模版样式

    问题: 我想在创建新的一些python程序的时候,希望在新文件开头添加python版本声明和一些关于时间相关的模版数据 那,如何解决? 1. pycharm ---> setting ---&g ...

  3. python 将pdf分页后插入至word中

    所用技术 1. python编程基础 2. 使用pyPdf 3. 使用python操作word 4. 正则表达式的使用 5. windows的bat编程 下面是一个pyPdf库使用的示例: from ...

  4. Python中dunder名称的来历

    版权声明:博客为作者原创,允许转载,但必须注明原文地址:https://www.cnblogs.com/byronxie/p/10741084.html 在 Python 中,我们经常会看到被双下划线 ...

  5. Python人工智能学习笔记

    Python教程 Python 教程 Python 简介 Python 环境搭建 Python 中文编码 Python 基础语法 Python 变量类型 Python 运算符 Python 条件语句 ...

  6. python爬虫积累(一)--------selenium+python+PhantomJS的使用(转)

    阅读目录 一.Selenium介绍 二.爬虫为什么要用selenium? 三.PhantomJS介绍 四.PhantomJS安装 五.操作实战 六.在此推荐虫师博客的学习资料 selenium + p ...

  7. python爬虫积累(一)--------selenium+python+PhantomJS的使用

    最近按公司要求,爬取相关网站时,发现没有找到js包的地址,我就采用selenium来爬取信息,相关实战链接:python爬虫实战(一)--------中国作物种质信息网 一.Selenium介绍 Se ...

  8. python操作word

    python教程(百度经验) Python 操作Word(Excel.PPT等通用)   import win32comfrom win32com.client import Dispatch, co ...

  9. python代码规范整理

    规范参考源: 1.pep8(python代码样式规范):中文文档      https://blog.csdn.net/ratsniper/article/details/78954852 2.pep ...

随机推荐

  1. 雪花算法生成ID

    前言我们的数据库在设计时一般有两个ID,自增的id为主键,还有一个业务ID使用UUID生成.自增id在需要分表的情况下做为业务主键不太理想,所以我们增加了uuid作为业务ID,有了业务id仍然还存在自 ...

  2. deepin 常见快捷键及常用命令

    常用命令 1)安装软件命令行:dpkg -i <.deb file name>示例:dpkg -i avg71flm_r28-1_i386.deb2)安装一个目录下面所有的软件包命令行:d ...

  3. 【洛谷P2647】最大收益

    题目大意 现在你面前有n个物品,编号分别为1,2,3,--,n.你可以在这当中任意选择任意多个物品.其中第i个物品有两个属性Wi和Ri,当你选择了第i个物品后,你就可以获得Wi的收益:但是,你选择该物 ...

  4. Python之常用模二(时间、序列号等等)

    一.time模块 表示时间的三种方式: 时间戳:数字(计算机能认识的) 时间字符串:t='2012-12-12' 结构化时间:time.struct_time(tm_year=2017, tm_mon ...

  5. Redhat 关闭防火墙和selinux

    查看防火墙状态.systemctl status firewalld 临时关闭防火墙命令.重启电脑后,防火墙自动起来.systemctl stop firewalld 永久关闭防火墙命令.重启后,防火 ...

  6. shell练习--PAT题目1008:数组元素循环右移问题 (失败案例,运行超时)

    一个数组A中存有N(>)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥)个位置,即将A中的数据由(A​0​​A​1​​⋯A​N−1​​)变换为(A​N−M​​⋯A​N−1​​A ...

  7. shell练习--关于关联数组自增统计判断的学习

    今天在书上看到了一个关联数组 let statarray["$ftype"]++  这样一个操作,用来做索引的自增统计,所以记下来 #!/bin/bash #统计文件类型 #关于关 ...

  8. 导出csv文件(使用a标签)

    https://blog.csdn.net/oscar999/article/details/16342699   productsCSV(e) { const { download } = this ...

  9. 代码检测docker-sonarqube

    gitlab-ce + gitlab-runner + sonarqube,在提交代码时对代码质量进行检测,对不符合要求的代码不允许提交到gitlab version: '3.1' services: ...

  10. druid配置以及监控

    1.druid监控的功能: . 数据源 . SQL监控 对执行的MySQL语句进行记录,并记录执行时间.事务次数等 . SQL防火墙 对SQL进行预编译,并统计该条SQL的数据指标 . Web应用 对 ...