转载

python操作excel

Openpyxl is a Python library for reading and writing Excel 2010 xlsx/xlsm/xltx/xltm files.

安装

$ pip install openpyxl

lxml library:pillow:在文件中需要使用images (jpeg, png, bmp,…)时,需要安装pillow库。

一个例子

IDLE新建.py文件

from openpyxl import Workbook 
wb = Workbook()
# 激活 worksheet
ws = wb.active
# 数据可以直接分配到单元格中
ws['A1'] = 42
# 可以附加行,从第一列开始附加
ws.append([1, 2, 3])
# Python 类型会被自动转换
import datetime
ws['A3'] = datetime.datetime.now().strftime("%Y-%m-%d")
# 保存文件
wb.save("sample.xlsx")

打开查看Excel如下:

A B C
1 42
2 1 2 3
3 2016-03-31

workbook

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

from openpyxl import Workbook
wb = Workbook()

worksheet

A workbook至少创建一个worksheet.

通过 openpyxl.workbook.Workbook.active() 得到worksheet.

ws = wb.active

注意:

该方法使用_active_sheet_index属性, 默认会设置0,也就是第一个worksheet。除非手动修改,否则使用active方法得到都是第一个worksheet。

你也可以创建worksheets,通过 openpyxl.workbook.Workbook.create_sheet() 方法:

>>> ws1 = wb.create_sheet("Mysheet") #插入到最后(default)
#或者
>>> ws2 = wb.create_sheet("Mysheet", 0) #插入到最开始的位置

创建的sheet的名称会自动创建,按照sheet,sheet1,sheet2自动增长,通过title属性可以修改其名称。

ws.title = "New Title"

默认的sheet的tab是白色的,可以通过 RRGGBB颜色来修改sheet_properties.tabColor属性从而修改sheet tab按钮的颜色:

ws.sheet_properties.tabColor = "1072BA"

当你设置了sheet的名称,可以将其看成workbook中的一个key。也可以使用 openpyxl.workbook.Workbook.get_sheet_by_name() 方法

>>> ws3 = wb["New Title"]
>>> ws4 = wb.get_sheet_by_name("New Title")
>>> ws is ws3 is ws4
True

查看workbook中的所有worksheets名称: openpyxl.workbook.Workbook.get_sheet_names()

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

遍历worksheets:

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

操作数据

访问单元格

单元格可以看作是worksheet的key,通过key去访问单元格中的数据

>>> c = ws['A4']

直接返回A4单元格,如果不存在则会自动创建一个。

指定单元格的值

>>> ws['A4'] = 4 #直接赋值

使用 openpyxl.worksheet.Worksheet.cell() 方法操作某行某列的某个值:

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

注意:

  1. 当worksheet在内存中被创建时,是没有包含cells的,cells是在首次访问时创建.
  2. 可以循环在内存中创建cells,这时不指定他们的值也会创建该cells些:(创建100x100cells)
>>> for i in range(1,101):
... for j in range(1,101):
... ws.cell(row=i, column=j)

访问许多cells

通过切片Ranges指定许多cells

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

同样也可以Ranges rows 或者columns :

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

也可以使用 openpyxl.worksheet.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>
同样的 openpyxl.worksheet.Worksheet.iter_cols() 方法返回columns:(血药指定列->列,截止行)
>>> 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>

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

Data storage

Once we have a openpyxl.cell.Cell, 指定其值:

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

可以指定其类型和格式:

>>> wb = Workbook(guess_types=True)
>>> c.value = '12%'
>>> print(c.value)
0.12
>>> import datetime
>>> d.value = datetime.datetime.now()
>>> print d.value
datetime.datetime(2010, 9, 10, 22, 25, 18)
>>> c.value = '31.50'
>>> print(c.value)
31.5

Saving to a file

最简单最安全的方法保存workbook是使用 openpyxl.workbook.Workbook 对象的 openpyxl.workbook.Workbook.save() 方法:

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

保存的默认位置在python的根目录下。

注意:会自动覆盖已经存在文件名的文件。

保存的时候不会强制保存为xlsx or xlsm格式,如果不保存为该格式的文件,使用其他的程序可能打不开。

也可以保存为zip格式,然后将文件解压出来。

保存为模板

指定属性 as_template=True,就可以将文档保存为模板.xltx

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

指定属性as_template=False (by default), 将模板保存为文档

>>> 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')
>>> # 需要保存为 *.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

Loading from a file

像写一样我们可以导入 openpyxl.load_workbook() 已经存在的workbook:

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

常用实例

使用公式

>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> ws = wb.active
>>> # add a simple formula
>>> ws["A1"] = "=SUM(1, 1)"
>>> wb.save("formula.xlsx")
原文  http://luciastar.com/2016/06/18/python操作Excel/
正文到此结束
Loading...