首页 > 代码库 > python openpyxl.md

python openpyxl.md

Openpyxl

创建一个工作簿

下面是创建一个工作簿。而每个工作簿至少一个工作表我们可以通过active获取正在运行的工作表。

In [1]: from openpyxl import Workbook

In [2]: wb = Workbook()

In [3]: ws = wb.active

In [4]: print(ws)
<Worksheet "Sheet">

新建一个工作表:

In [5]: ws1 = wb.create_sheet()  #默认插在工作簿末尾

In [6]: print(ws1)
<Worksheet "Sheet1">

In [7]: ws2 = wb.create_sheet(0)  #插入在工作簿的第一个位置

In [8]: print(ws2)
<Worksheet "Sheet2">

修改工作表名:

In [9]: print(ws.title)
Sheet

In [10]: ws.title = ‘New Title‘

In [11]: print(ws.title)
New Title

一旦你获取工作表的名字,你可以通过workbook的key或者 openpyxl.workbook.Workbook.get_sheet_by_name() 方法得到该工作表

In [13]: ws3 = wb[‘New Title‘]

In [14]: ws4 = wb.get_sheet_by_name(‘New Title‘)

In [15]: ws is ws3
Out[15]: True

In [16]: ws is ws4
Out[16]: True

你可以通过openpyxl.workbook.Workbook.get_sheet_names() 方法得到工作簿的所有工作表。

In [20]: print(wb.get_sheet_names())
[‘New Title‘, ‘Sheet1‘, ‘Sheet2‘]

In [32]: print(wb.sheetnames)
[‘New Title‘, ‘Sheet1‘, ‘Sheet2‘]

你也可以循环得到所有的工作表:

In [21]: for sheet in wb:
    ...:     print(sheet.title)
    ...:     
New Title
Sheet1
Sheet2

可以在一个工作簿中创建工作表的副本:

In [33]: source = wb.active

In [34]: target = wb.copy_worksheet(source)

In [35]: print(target)
<Worksheet "New Title Copy">

In [36]: wb.get_sheet_names()
Out[36]: [‘New Title‘, ‘Sheet1‘, ‘Sheet2‘, ‘New Title Copy‘]

操作数据

单元格可以直接根据他们的索引直接获得:

In [22]: c = ws[‘A4‘]

通过上述的语句,将返回在A4处的单元格,如果不存在将在A4新建一个。 单元格的值也可以直接赋值

In [24]: ws[‘A4‘] = 4

这提供了使用行和列符号来访问单元格的方法:

In [26]: d = ws.cell(row = 4,column = 2,value=http://www.mamicode.com/10)

注意:当一个工作表被创建是,其中不包含单元格。只有当单元格被获取是才被创建。这种方式我们不会创建我们从不会使用的单元格,从而减少了内存消耗。
警告:由于上述特性,你如果遍历了单元格而非想要使用它们也将会在内存当中创建。

使用切片获取多个单元格:

In [31]: cell_range = ws[‘A1‘:‘C2‘]

行或列的范围可以类似地获得:

In [37]: colC = ws[‘C‘]

In [38]: col_range = ws[‘C:D‘]

In [39]: row10 = ws[10]

In [40]: row_range = ws[5:10]

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

In [41]: for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
    ...:     for cell in row:
    ...:         print(cell)
    ...:         
<Cell ‘New Title‘.A1>
<Cell ‘New Title‘.B1>
<Cell ‘New Title‘.C1>
<Cell ‘New Title‘.A2>
<Cell ‘New Title‘.B2>
<Cell ‘New Title‘.C2>

同样openpyxl.worksheet.Worksheet.iter_cols()方法将返回列:

In [42]: for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
    ...:     for cell in col:
    ...:         print(cell)
    ...:         
<Cell ‘New Title‘.A1>
<Cell ‘New Title‘.A2>
<Cell ‘New Title‘.B1>
<Cell ‘New Title‘.B2>
<Cell ‘New Title‘.C1>
<Cell ‘New Title‘.C2>

如果你需要遍历所有行或列的一个文件,您可以使用openpyxl.worksheet.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>))

或openpyxl.worksheet.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>))

数据存储

一旦我们有一个openpyxl.cell.Cell,我们可以直接为该单元格赋值:

In [47]: c.value = http://www.mamicode.com/‘hello, world‘

In [48]: print(c.value)
hello, world

In [49]: d.value = http://www.mamicode.com/3.14

In [50]: print(d.value)
3.14

保存到文件

保存工作簿最简单最安全的方式是使用openpyxl.workbook.Workbook的openpyxl.workbook.Workbook.save() 方法

In [57]: wb = Workbook()

In [58]: wb.save(‘test.xlsx‘)

这个操作将会在没有警告的情况下覆盖现有的文件。

你也可以 as_template=True,将文件保存称为一个模板:

>>> wb = load_workbook(‘document.xlsx‘)
>>> wb.save(‘document_template.xltx‘, as_template=True)

如果as_template=False(默认),则将文件或模板保存为文件:

>>> wb = load_workbook(‘document_template.xltx‘)
>>> wb.save(‘document.xlsx‘, as_template=False)
>>> wb = load_workbook(‘document.xlsx‘)
>>> wb.save(‘new_document.xlsx‘, as_template=False)

警告:在保存文件到文件模板中的时候你应该监控数据的属性和文件扩展名,反之亦然;否则,你得到的工作簿可能无法打开。

>>> 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 can‘t open the document
>>>
>>> # or
>>>
>>> wb = load_workbook(‘document.xltm‘, keep_vba=True)
>>> # If us need template document, then we need specify extension as *.xltm.
>>> # If us need document, then we need specify attribute as_template=False.
>>> wb.save(‘new_document.xlsm‘, as_template=True)
>>> # MS Excel can‘t open the document

从文件中导入

和写入文件的方式相同,你可以引入openpyxl.load_workbook()来打开一个已经存在的工作簿

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

使用举例

Write a workbook

from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.utils import get_column_letter

wb = Workbook()
dest_filename = ‘D:\excel\empty_book.xlsx‘
ws1 = wb.active
ws1.title = "range names"
for row in range(1, 40):
    ws1.append(range(600))

ws2 = wb.create_sheet(title="Pi")
ws2[‘F5‘] = 3.14
ws3 = wb.create_sheet(title="Data")
for row in range(10, 20):
    for col in range(27, 54):
        _ = ws3.cell(column=col, row=row, value=http://www.mamicode.com/"{0}".format(get_column_letter(col)))

wb.save(filename = dest_filename)

Read an existing workbook

>>> from openpyxl import load_workbook
>>> wb = load_workbook(filename = ‘empty_book.xlsx‘)
>>> sheet_ranges = wb[‘range names‘]
>>> print(sheet_ranges[‘D18‘].value)
3

Using number formats

In [1]: import datetime

In [2]: from openpyxl import Workbook

In [3]: wb = Workbook()

In [4]: ws = wb.active

In [5]: ws[‘A1‘] = datetime.datetime(2010, 7, 21)

In [6]: ws[‘A1‘].number_format
Out[6]: ‘yyyy-mm-dd h:mm:ss‘

In [7]: wb.guess_types = True

In [8]: ws[‘B1‘] = ‘3.14%‘

In [9]: wb.guess_types = False

In [10]: ws[‘B1‘].value
Out[10]: 0.031400000000000004

In [11]: ws[‘B1‘].number_format
Out[11]: ‘0%‘

Using formulae

In [1]: from openpyxl import Workbook

In [2]: wb = Workbook()

In [3]:  ws = wb.active

In [4]: ws["A1"] = "=SUM(1, 1)"

In [5]: wb.save("formula.xlsx")

注意,你必须使用英文名作为一个函数,函数参数必须用逗号分开,而不是像半冒号那样的其他标点符号。
openpyxl从不计算公式,但可以检查公式的名称:

>>> from openpyxl.utils import FORMULAE
>>> "HEX2DEC" in FORMULAE
True

如果你试图使用一个未知的公式,这可能是因为你使用的公式没有包含在初始规范中。这样的公式必须用xlfn进行前缀。去工作。

Merge / Unmerge cells

当您将所有的单元合并时,但是左上角的单元格将从工作表中删除。请参阅样式合并的单元以获得关于格式化合并单元的信息。

>>> from openpyxl.workbook import Workbook
>>> wb = Workbook()
>>> ws = wb.active
>>> ws.merge_cells(‘A1:B1‘)
>>> ws.unmerge_cells(‘A1:B1‘)
>>> # or
>>> ws.merge_cells(start_row=2,start_column=1,end_row=2,end_column=4)
>>> ws.unmerge_cells(start_row=2,start_column=1,end_row=2,end_column=4)

Inserting an image

>>> from openpyxl import Workbook
>>> from openpyxl.drawing.image import Image
>>> wb = Workbook()
>>> ws = wb.active
>>> ws[‘A1‘] = ‘You should see three logos below‘
>>> # create an image
>>> img = Image(‘logo.png‘)
>>> # add to worksheet and anchor next to cells
>>> ws.add_image(img, ‘A1‘)
>>> wb.save(‘logo.xlsx‘)

Fold columns (outline)

>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> ws = wb.create_sheet()
>>> ws.column_dimensions.group(‘A‘,‘D‘, hidden=True)
>>> wb.save(‘group.xlsx‘)

python openpyxl.md