OpenPyXL 3.0.7
  • 教程
  • 简单用法
  • 性能
  • 优化模式
  • 插入和删除行和列,移动单元格范围
  • 操纵 Pandas 和 NumPy
  • 图表
  • 注释
  • 操控样式
  • 额外工作表特性
  • 条件格式化
  • 数据透视表
  • 打印设置
  • 使用过滤器和排序
  • 验证单元格
  • 定义名称
  • 工作表表格
  • 剖析公式
  • 日期和时间
  • 保护
  • 开发
  • openpyxl 包
  • 3.0.7 (2021-03-09)
  • 3.0.6 (2021-01-14)
  • 3.0.5 (2020-08-21)
  • 3.0.4 (2020-06-24)
  • 3.0.3 (2020-01-20)
  • 3.0.2 (2019-11-25)
  • 3.0.1 (2019-11-14)
  • 3.0.0 (2019-09-25)
  • 2.6.4 (2019-09-25)
  • 2.6.3 (2019-08-19)
  • 2.6.2 (2019-03-29)
  • 2.6.1 (2019-03-04)
  • 2.6.0 (2019-02-06)
  • 2.6.-b1 (2019-01-08)
  • 2.6-a1 (2018-11-21)
  • 2.5.14 (2019-01-23)
  • 2.5.13 (brown bag)
  • 2.5.12 (2018-11-29)
  • 2.5.11 (2018-11-21)
  • 2.5.10 (2018-11-13)
  • 2.5.9 (2018-10-19)
  • 2.5.8 (2018-09-25)
  • 2.5.7 (2018-09-13)
  • 2.5.6 (2018-08-30)
  • 2.5.5 (2018-08-04)
  • 2.5.4 (2018-06-07)
  • 2.5.3 (2018-04-18)
  • 2.5.2 (2018-04-06)
  • 2.5.1 (2018-03-12)
  • 2.5.0 (2018-01-24)
  • 2.5.0-b2 (2018-01-19)
  • 2.5.0-b1 (2017-10-19)
  • 2.5.0-a3 (2017-08-14)
  • 2.5.0-a2 (2017-06-25)
  • 2.5.0-a1 (2017-05-30)
  • 2.4.11 (2018-01-24)
  • 2.4.10 (2018-01-19)
  • 2.4.9 (2017-10-19)
  • 2.4.8 (2017-05-30)
  • 2.4.7 (2017-04-24)
  • 2.4.6 (2017-04-14)
  • 2.4.5 (2017-03-07)
  • 2.4.4 (2017-02-23)
  • 2.4.3 (未发行)
  • 2.4.2 (2017-01-31)
  • 2.4.1 (2016-11-23)
  • 2.4.0 (2016-09-15)
  • 2.4.0-b1 (2016-06-08)
  • 2.4.0-a1 (2016-04-11)
  • 2.3.5 (2016-04-11)
  • 2.3.4 (2016-03-16)
  • 2.3.3 (2016-01-18)
  • 2.3.2 (2015-12-07)
  • 2.3.1 (2015-11-20)
  • 2.3.0 (2015-10-20)
  • 2.3.0-b2 (2015-09-04)
  • 2.3.0-b1 (2015-06-29)
  • 2.2.6 (未发行)
  • 2.2.5 (2015-06-29)
  • 2.2.4 (2015-06-17)
  • 2.2.3 (2015-05-26)
  • 2.2.2 (2015-04-28)
  • 2.2.1 (2015-03-31)
  • 2.2.0 (2015-03-11)
  • 2.2.0-b1 (2015-02-18)
  • 2.1.5 (2015-02-18)
  • 2.1.4 (2014-12-16)
  • 2.1.3 (2014-12-09)
  • 2.1.2 (2014-10-23)
  • 2.1.1 (2014-10-08)
  • 2.1.0 (2014-09-21)
  • 2.0.5 (2014-08-08)
  • 2.0.4 (2014-06-25)
  • 2.0.3 (2014-05-22)
  • 2.0.2 (2014-05-13)
  • 2.0.1 (2014-05-13) brown bag
  • 2.0.0 (2014-05-13) brown bag
  • 1.8.6 (2014-05-05)
  • 1.8.5 (2014-03-25)
  • 1.8.4 (2014-02-25)
  • 1.8.3 (2014-02-09)
  • 1.8.2 (2014-01-17)
  • 1.8.1 (2014-01-14)
  • 1.8.0 (2014-01-08)
  • 1.7.0 (2013-10-31)
  • 教程

    创建工作薄

    There is no need to create a file on the filesystem to get started with openpyxl. Just import the Workbook class and start work:

    >>> from openpyxl import Workbook
    >>> wb = Workbook()
    					

    A workbook is always created with at least one worksheet. You can get it by using the Workbook.active 特性:

    >>> ws = wb.active
    					

    注意

    This is set to 0 by default. Unless you modify its value, you will always get the first worksheet by using this method.

    You can create new worksheets using the Workbook.create_sheet() 方法:

    >>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
    # or
    >>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
    # or
    >>> ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position
    					

    Sheets are given a name automatically when they are created. They are numbered in sequence (Sheet, Sheet1, Sheet2, …). You can change this name at any time with the Worksheet.title 特性:

    ws.title = "New Title"
    					

    The background color of the tab holding this title is white by default. You can change this providing an RRGGBB color code to the Worksheet.sheet_properties.tabColor 属性:

    ws.sheet_properties.tabColor = "1072BA"
    					

    Once you gave a worksheet a name, you can get it as a key of the workbook:

    >>> ws3 = wb["New Title"]
    					

    You can review the names of all worksheets of the workbook with the Workbook.sheetname 属性

    >>> print(wb.sheetnames)
    ['Sheet2', 'New Title', 'Sheet1']
    					

    You can loop through worksheets

    >>> for sheet in wb:
    ...     print(sheet.title)
    					

    You can create copies of worksheets within a single workbook :

    Workbook.copy_worksheet() 方法:

    >>> source = wb.active
    >>> target = wb.copy_worksheet(source)
    					

    注意

    Only cells (including values, styles, hyperlinks and comments) and certain worksheet attribues (including dimensions, format and properties) are copied. All other workbook / worksheet attributes are not copied - e.g. Images, Charts.

    You also cannot copy worksheets between workbooks. You cannot copy a worksheet if the workbook is open in 只读 or write-only 模式。

    处理数据

    访问一单元格

    Now we know how to get a worksheet, we can start modifying cells content. Cells can be accessed directly as keys of the worksheet:

    >>> c = ws['A4']
    					

    This will return the cell at A4, or create one if it does not exist yet. Values can be directly assigned:

    >>> ws['A4'] = 4
    					

    There is also the Worksheet.cell() 方法。

    This provides access to cells using row and column notation:

    >>> d = ws.cell(row=4, column=2, value=10)
    					

    注意

    When a worksheet is created in memory, it contains no cells . They are created when first accessed.

    警告

    Because of this feature, scrolling through cells instead of accessing them directly will create them all in memory, even if you don’t assign them a value.

    Something like

    >>> for x in range(1,101):
    ...        for y in range(1,101):
    ...            ws.cell(row=x, column=y)
    					

    will create 100x100 cells in memory, for nothing.

    访问多单元格

    Ranges of cells can be accessed using slicing:

    >>> cell_range = ws['A1':'C2']
    					

    Ranges of rows or columns can be obtained similarly:

    >>> colC = ws['C']
    >>> col_range = ws['C:D']
    >>> row10 = ws[10]
    >>> row_range = ws[5:10]
    					

    还可以使用 Worksheet.iter_rows() 方法:

    >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
    ...    for cell in row:
    ...        print(cell)
    <Cell Sheet1.A1>
    <Cell Sheet1.B1>
    <Cell Sheet1.C1>
    <Cell Sheet1.A2>
    <Cell Sheet1.B2>
    <Cell Sheet1.C2>
    					

    Likewise the Worksheet.iter_cols() method will return columns:

    >>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
    ...     for cell in col:
    ...         print(cell)
    <Cell Sheet1.A1>
    <Cell Sheet1.A2>
    <Cell Sheet1.B1>
    <Cell Sheet1.B2>
    <Cell Sheet1.C1>
    <Cell Sheet1.C2>
    					

    注意

    For performance reasons the Worksheet.iter_cols() method is not available in read-only mode.

    If you need to iterate through all the rows or columns of a file, you can instead use the Worksheet.rows 特性:

    >>> ws = wb.active
    >>> ws['C9'] = 'hello world'
    >>> tuple(ws.rows)
    ((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
    (<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
    (<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>),
    (<Cell Sheet.A4>, <Cell Sheet.B4>, <Cell Sheet.C4>),
    (<Cell Sheet.A5>, <Cell Sheet.B5>, <Cell Sheet.C5>),
    (<Cell Sheet.A6>, <Cell Sheet.B6>, <Cell Sheet.C6>),
    (<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>),
    (<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
    (<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))
    					

    Worksheet.columns 特性:

    >>> tuple(ws.columns)
    ((<Cell Sheet.A1>,
    <Cell Sheet.A2>,
    <Cell Sheet.A3>,
    <Cell Sheet.A4>,
    <Cell Sheet.A5>,
    <Cell Sheet.A6>,
    ...
    <Cell Sheet.B7>,
    <Cell Sheet.B8>,
    <Cell Sheet.B9>),
    (<Cell Sheet.C1>,
    <Cell Sheet.C2>,
    <Cell Sheet.C3>,
    <Cell Sheet.C4>,
    <Cell Sheet.C5>,
    <Cell Sheet.C6>,
    <Cell Sheet.C7>,
    <Cell Sheet.C8>,
    <Cell Sheet.C9>))
    					

    注意

    For performance reasons the Worksheet.columns property is not available in read-only mode.

    仅值

    If you just want the values from a worksheet you can use the Worksheet.values property. This iterates over all the rows in a worksheet but returns just the cell values:

    for row in ws.values:
       for value in row:
         print(value)
    					

    Both Worksheet.iter_rows() and Worksheet.iter_cols() can take the values_only parameter to return just the cell’s value:

    >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
    ...   print(row)
    (None, None, None)
    (None, None, None)
    					

    数据存储

    Once we have a Cell , we can assign it a value:

    >>> c.value = 'hello, world'
    >>> print(c.value)
    'hello, world'
    >>> d.value = 3.14
    >>> print(d.value)
    3.14
    					

    保存到文件

    The simplest and safest way to save a workbook is by using the Workbook.save() 方法在 Workbook 对象:

    >>> wb = Workbook()
    >>> wb.save('balances.xlsx')
    					

    警告

    This operation will overwrite existing files without warning.

    注意

    The filename extension is not forced to be xlsx or xlsm, although you might have some trouble opening it directly with another application if you don’t use an official extension.

    As OOXML files are basically ZIP files, you can also open it with your favourite ZIP archive manager.

    另存为流

    If you want to save the file to a stream, e.g. when using a web application such as Pyramid, Flask or Django then you can simply provide a NamedTemporaryFile() :

    >>> from tempfile import NamedTemporaryFile
    >>> from openpyxl import Workbook
    >>> wb = Workbook()
    >>> with NamedTemporaryFile() as tmp:
            wb.save(tmp.name)
            tmp.seek(0)
            stream = tmp.read()
    					

    You can specify the attribute template=True , to save a workbook as a template:

    >>> wb = load_workbook('document.xlsx')
    >>> wb.template = True
    >>> wb.save('document_template.xltx')
    					

    or set this attribute to False (default), to save as a document:

    >>> wb = load_workbook('document_template.xltx')
    >>> wb.template = False
    >>> wb.save('document.xlsx', as_template=False)
    					

    警告

    You should monitor the data attributes and document extensions for saving documents in the document templates and vice versa, otherwise the result table engine can not open the document.

    注意

    The following will fail:

    >>> wb = load_workbook('document.xlsx')
    >>> # Need to save with the extension *.xlsx
    >>> wb.save('new_document.xlsm')
    >>> # MS Excel can't open the document
    >>>
    >>> # or
    >>>
    >>> # Need specify attribute keep_vba=True
    >>> wb = load_workbook('document.xlsm')
    >>> wb.save('new_document.xlsm')
    >>> # MS Excel will not open the document
    >>>
    >>> # or
    >>>
    >>> wb = load_workbook('document.xltm', keep_vba=True)
    >>> # If we need a template document, then we must specify extension as *.xltm.
    >>> wb.save('new_document.xlsm')
    >>> # MS Excel will not open the document
    					

    加载从文件

    The same way as writing, you can use the openpyxl.load_workbook() to open an existing workbook:

    >>> from openpyxl import load_workbook
    >>> wb2 = load_workbook('test.xlsx')
    >>> print(wb2.sheetnames)
    ['Sheet2', 'New Title', 'Sheet1']
    					

    This ends the tutorial for now, you can proceed to the 简单用法 section