python excel openpyxl_python3操作Excel openpyxl模块的使用

python 与excel

安装模块

本例子中使用的模块为:

openpyxl

版本为2.4.8

安装方法请参看以前发表的文章(Python 的pip模块安装方法)

Python处理Excel表格

使用模块:openpyxl(2.4.8)

基本使用方法

1.首先导入模块:import openpyxl

2.打开一个已经存在的excel文件:

wb=openpyxl.load_workbook(‘example.xlsx‘)

(文件和脚本放在同一个目录下,如果不是的话需要加上路径

wb=wpenpyxl.load_workbook(r‘c:\maxingpython\example.xlsx‘))

此时wb是一个workbook对象,表示的是整个Excel文件,类似于file对象表示一个文本文件。

3.获取Excel文件中具体的表:

sheet=wb.get_sheet_name(‘Sheet1‘)#根据表名获取

sheet=wb[‘Sheet1’]#更简洁的方法

sheet=wb.get_active_sheet()#获取当前激活的表(即打开Excel默认打开的表)

sheet=wb.active#通过属性获取当前激活的表

Sheet.title可以得到表的名字。

4.获取表中的行与列

sheet.rows

sheet.columns

注意这里获取的行与列是一个生成器对象:

>>> sheet.rows

5.获取表的总行数与总列数

总行数:len(list(sheet.rows)) 总列数:len(list(sheet.columns))

直接调用属性:sheet.max_row;sheet.max_column

6.获取单元格对象

cell=sheet[‘A1’]#获取了一个单元格对象

cell.value#获取该单元格的值

这种方法是使用Excel种默认的行(数字)与列(字母)的形式来获取对应的单元格。

另外一种方式是直接指定命名参数:

cell=sheet.cell(row=2,column=2)

cell.value#获取单元格的值

cell.row#获取相应的行

cell.column#获取相应的列

cell.cordinate#获取相应的坐标

例子

>>> cell=sheet.cell(row=2,column=2)

>>> cell.value

‘苹果‘

>>> cell.row

2

>>> cell.column

‘B‘

>>> cell.coordinate

‘B2‘

这种方法都是用数字来表示行与列(第一行为1不是0)

这两种工具互转化:

>>> openpyxl.utils.cell.column_index_from_string(‘A‘)

1

>>> openpyxl.utils.cell.column_index_from_string(‘AC‘)

29

>>> openpyxl.utils.cell.get_column_letter(1)

‘A‘

>>> openpyxl.utils.cell.get_column_letter(29)

‘AC‘

>>>

7.获取某一个区域的数据

>>> sheet[‘A1:C3‘]

((, , ), (, , ), (, , ))

>>> type(sheet[‘A1:C3‘])

>>> import pprint#上面打印太乱,导入漂亮打印模块

>>> pprint.pprint(sheet[‘A1:C3‘])

((, , ),

(, , ),

(, , ))

注意到sheet[‘A1:C3‘]获取到的是一个元组组成的元组。

8.获取所有的表名

>>> wb.get_sheet_names()

[‘my first sheet‘]

返回的是一个列表。

向表格中写入数据

1.新建一个Excel文件

>>> from openpyxl import Workbook

>>> wb=Workbook()

>>> wb

这样便创建了一个Workbook对象,实际上还没有生成Excel文件,要实际生成该Excel文件需要调用save函数之后。

默认Workbook对象将创建一张表“sheet”

>>> wb.active

>>> sheet=wb.active

>>> sheet.title=‘my first sheet‘

>>> sheet.title

‘my first sheet‘

通过sheet.title属性可以修改表名。

2.保存

>>> wb.save(‘test.xlsx‘)

此时在工作目录下才会生成test.xlsx文件。

3.增加及删除表

>>> wb.create_sheet()

>>> wb.get_sheet_names()

[‘Sheet‘, ‘Sheet1‘]

>>> wb.create_sheet(‘names‘)

>>> wb.get_sheet_names()

[‘Sheet‘, ‘Sheet1‘, ‘names‘]

>>> wb.create_sheet(index=0,title=‘first tab‘)

>>> wb.get_sheet_names()

[‘first tab‘, ‘Sheet‘, ‘Sheet1‘, ‘names‘]

>>> wb.create_sheet(index=len(wb.get_sheet_names()),title=‘last tab‘)

>>> wb.get_sheet_names()

[‘first tab‘, ‘Sheet‘, ‘Sheet1‘, ‘names‘, ‘last tab‘]

>>> wb.remove_sheet(wb[‘first tab‘])

>>> wb.get_sheet_names()

[‘Sheet‘, ‘Sheet1‘, ‘names‘, ‘last tab‘]

4.向单元格中写入信息

>>> sheet[‘A1‘]=‘Hello world!‘

>>> sheet.cell(row=2,column=2).value=‘张三‘

>>> sheet[‘B2‘].value

‘张三‘

5.单元格字体风格

首先要导入相应的函数:

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)

>>>

例子:

为单元格设置样式

>>> cell1=sheet[‘A1‘]

>>> cell2=sheet[‘A2‘]

>>> ft1=Font(color=colors.RED)

>>> ft2=Font(color=‘00FF00‘,size=30)

>>> cell1.font=ft1

>>> cell2.font=ft2

复制样式:

>>> fromopenpyxl.stylesimportFont

>>> fromcopyimportcopy

>>>

>>> ft1=Font(name=‘Arial‘, size=14)

>>> ft2=copy(ft1)

>>> ft2.name=‘Tahoma‘

>>> ft1.name‘Arial‘

>>> ft2.name‘Tahoma‘

>>> ft2.size# copied from the14.0

自定义样式:

>>> from openpyxl.styles import NamedStyle, Font, Border, Side

>>> highlight = NamedStyle(name=‘highlight‘)

>>> highlight.font = Font(bold=True, size=20)

>>> bd = Side(style=‘thick‘, color=‘000000‘)

>>> highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)

创建好后便可以应用到workbook了

>>> wb.add_named_style(highlight)#第一步

>>> ws[‘A1‘].style = highlight#第二步

Once registered assign the style using just the name:

>>> ws[‘D5‘].style = ‘highlight‘#以后就可以直接调用字符串形式了

7.合并与拆分单元格

import openpyxl

wb=openpyxl.load_workbook(‘two.xlsx‘)

sheet=wb.active

sheet.merge_cells(‘A1:A2‘)

wb.save(‘three.xlsx‘)

同理拆开单元格便是sheet.unmerge_cells(‘A1:A2‘),但是在交互式环境中可以,写在py文件中就会报错,不知什么原因。

原文地址:http://www.cnblogs.com/gy-ph/p/7827151.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值