python-通过openpy操作excel
1.安装 openpyxl
pip install openpyxl == 2.3.5 安装指定版本
遇到问题:
查询结果:这是因为电脑上有其他软件也有pip命令,我的电脑上是因为装了loadrunner
解决办法:
我用的有效命令:
python -m pip install openpyxl 安装成功
2.安装pillow
直接点击安装即可,64位需要和python版本一致;32也是
3.show openpyxl
c:\Python27>python -m pip show openpyxl
4.创建excel文件对象
>>> from openpyxl import *
>>> wb = Workbook() #创建excel文件对象,写在内存里的,不保存的话在关闭后就没了
>>> ws = wb.active #获取excel文件的一个sheet
>>> ws['A1']=12 #写入内容 单格写
>>> ws['A2']=12.333
>>> ws['A3']=u"小七"
>>> wb.save("e:\\test1.xlsx") #保存文件
>>> ws["B1"]=u"哥哥"
>>> ws["B2"]=u"我想我哥哥了"
>>> wb.save("e:\\test1.xlsx")
>>> import time #写入时间
>>> ws["c1"]= time.strftime(u"%Y年%m月%d日 %H时%M分%S秒".encode("utf-8"),time.lo
caltime())
>>> wb.save("e:\\test1.xlsx")
import datetime
import time
ws['A2'] = datetime.datetime.now()
5.打印有效行和列:
>>> ws.columns
<generator object _cells_by_col at
0x0000000002E117E0>
>>> for col in ws.columns:
...
print col
...
(<Cell u'Sheet'.A1>, <Cell
u'Sheet'.A2>, <Cell u'Sheet'.A3>)
(<Cell u'Sheet'.B1>, <Cell
u'Sheet'.B2>, <Cell u'Sheet'.B3>)
(<Cell u'Sheet'.C1>, <Cell
u'Sheet'.C2>, <Cell u'Sheet'.C3>)
>>> for col in ws.rows:
...
print col
...
(<Cell u'Sheet'.A1>, <Cell
u'Sheet'.B1>, <Cell u'Sheet'.C1>)
(<Cell u'Sheet'.A2>, <Cell
u'Sheet'.B2>, <Cell u'Sheet'.C2>)
(<Cell u'Sheet'.A3>, <Cell
u'Sheet'.B3>, <Cell u'Sheet'.C3>)
什么是有效行和列?
数据写入的可包含整体数据的最大范围,这个范围内的都是有效行和列
6.创建sheet
>>> ws = wb.create_sheet("gloryroad")
>>> ws = wb.create_sheet("I
love")
>>> ws = wb.create_sheet(u"哥哥")
>>>
wb.save("e:\\test.xlsx")
7.获取sheet名称
>>> wb.get_sheet_names() #获取所有名称
[u'Sheet', u'gloryroad', u'I love',
u'\u54e5\u54e5']
>>> ws =
wb.get_sheet_by_name(u"哥哥") #获取指定名称
>>> ws
<Worksheet "\u54e5\u54e5">
>>> print
ws.encode("gbk")
>>> ws =
wb.get_sheet_by_name(wb.get_sheet_names()[-1])
#获取指定位置的sheet名称
>>> ws
<Worksheet "\u54e5\u54e5">
8.修改sheet名称
>>> ws =
wb.get_sheet_by_name(wb.get_sheet_names()[-1])
#修改前需要先获取
>>> ws
<Worksheet "\u54e5\u54e5">
>>> ws.title = "lin"
>>> wb.get_sheet_names()
[u'Sheet', u'gloryroad', u'I love', u'lin']
>>> ws.title
u'lin'
9.获取sheet名称
>>> ws = wb["I love"]
>>> ws
<Worksheet "I love">
>>> wb.sheetnames
[u'Sheet', u'gloryroad', u'I love', u'lin']
10. 通过行和列修改表格内的内容
>>>
ws.cell(row=1,column=2,value=123456)
<Cell u'I love'.B1>
>>> ws["B1"].value
123456
>>>
ws.cell(row=1,column=2,value="I love")
<Cell u'I love'.B1>
>>> ws["B1"].value
u'I love'
小练习:
从A1到D4区域的所有单元格都要写内容,内容是行号是第一位,列号是第二位
>>> for row in range(1,5):
...
for col in range(1,5):
...
ws.cell(row=row,column=col,value=str(row)+str(col))
...
<Cell u'I love'.A1>
<Cell u'I love'.B1>
<Cell u'I love'.C1>
<Cell u'I love'.D1>
<Cell u'I love'.A2>
<Cell u'I love'.B2>
<Cell u'I love'.C2>
<Cell u'I love'.D2>
<Cell u'I love'.A3>
<Cell u'I love'.B3>
<Cell u'I love'.C3>
<Cell u'I love'.D3>
<Cell u'I love'.A4>
<Cell u'I love'.B4>
<Cell u'I love'.C4>
<Cell u'I love'.D4>
>>>
wb.save("e:\\test.xlsx")
>>>
11. 操作某列中所有有效数据
>>> print ws["A"]
(<Cell u'I love'.A1>, <Cell u'I
love'.A2>, <Cell u'I love'.A3>, <Cell u'I love'.
A4>)
12. 操作某两列之间的所有有效值
>>> print ws["A:D"]
((<Cell u'I love'.A1>, <Cell u'I
love'.A2>, <Cell u'I love'.A3>, <Cell u'I love'
.A4>), (<Cell u'I love'.B1>,
<Cell u'I love'.B2>, <Cell u'I love'.B3>, <Cell u'I
love'.B4>), (<Cell u'I love'.C1>,
<Cell u'I love'.C2>, <Cell u'I love'.C3>, <Ce
ll u'I love'.C4>), (<Cell u'I
love'.D1>, <Cell u'I love'.D2>, <Cell u'I love'.D3
>, <Cell u'I love'.D4>))
13. 打印出获取到的指定位置的值
>>> print
ws["A:D"][0][0].value
11
>>>
ws["A:D"][0][0].value='22' 第一列的第一行:列在前,行在后
14. 取出列的值;取出行和列的值
>>> ws[1] 取出1行
(<Cell u'I love'.A1>, <Cell u'I
love'.B1>, <Cell u'I love'.C1>, <Cell u'I love'.
D1>)
>>> ws[1:2] 取出1行2列的值
((<Cell u'I love'.A1>, <Cell u'I
love'.B1>, <Cell u'I love'.C1>, <Cell u'I love'
.D1>), (<Cell u'I love'.A2>,
<Cell u'I love'.B2>, <Cell u'I love'.C2>, <Cell u'I
love'.D2>))
小练习:取出1到3行的内容
自己的做法,取了3列
>>> for i in range(1,3):
...
print ws[i:3]
...
((<Cell u'I love'.A1>, <Cell u'I
love'.B1>, <Cell u'I love'.C1>, <Cell u'I love'
.D1>), (<Cell u'I love'.A2>,
<Cell u'I love'.B2>, <Cell u'I love'.C2>, <Cell u'I
love'.D2>), (<Cell u'I love'.A3>,
<Cell u'I love'.B3>, <Cell u'I love'.C3>, <Ce
ll u'I love'.D3>))
((<Cell u'I love'.A2>, <Cell u'I
love'.B2>, <Cell u'I love'.C2>, <Cell u'I love'
.D2>), (<Cell u'I love'.A3>,
<Cell u'I love'.B3>, <Cell u'I love'.C3>, <Cell u'I
love'.D3>))
老师的方法:
>>> for row in ws[1:3]:
... for j in range(len(row)): 利用每行元素的个数来确定有多少列
... print row[j].value
同学的方法:
for rows in ws[1:3]:
for row in rows:
print row.value,
print
15. 指定一个范围,通过限制最大行号和列号,最小行号和列号来实现
>>> for row in ws.iter_rows(min_row=1,max_col=3,max_row=3):
...
for cell in row:
...
print cell.value
...
22
12
13
21
22
23
31
32
33
>>> for row in ws.iter_rows(min_row=1,min_col=1,max_col=3,max_row=3):
...
for cell in row:
...
print cell.value
...
16. 打印所有的行和列
>>> for row in ws.rows: 打印所有的行
...
print row
...
>>> for col in ws.columns: 打印所有的列
...
print col
...
17. 写入百分数
>>> ws["Z100"]="66%"
>>> print
ws["Z100"].value
66%
>>> wb.guess_type = True 为True时excel里面就是常规类型,为False时是百分数?
>>> ws["Z101"].value
>>>
wb.save("e:\\test.xlsx")
18. 修改excel里面的值
>>> wb =
load_workbook("e:\\test.xlsx")
#读取一个现有的文件进行操作
>>> ws = wb.active #获取当前sheet
>>> ws['A1'].vlue
>>> ws['A1'].value
12L
>>> ws['A1'].value=12 #修改值
>>> ws['A1'].value
12
>>> ws['A2'].value
12.333
>>>
ws['A2'].value=u"gege" #修改值
>>> ws['A2'].value
u'gege'
19. 判断excel内存储的数值格式类型
>>> ws['A3'].value =
"12%"
>>> ws['A3'].number_format
'General'
>>> ws['A20'].number_format
'General'
>>> wb.guess_type = True
>>> ws['A10']="12%"
>>> ws['A10'].number_format
'General'
>>> ws['A10']="12%"
>>>
wb.save("e:\\test.xslx")
>>> ws['A10'].number_format
'General'
>>> import datetime
>>>
ws["A11"]=datetime.datetime(1017,1,1)
>>> ws['A11'].number_format
'yyyy-mm-dd h:mm:ss'
>>>
20. 写入一个sum函数
>>> ws["A11"]="=sum(1,1)"
>>> print ws["A11"]
<Cell u'Sheet'.A11>
>>> print ws["A11"].value
=sum(1,1)
>>> wb.save("e:\\sample.xlsx")
21. 合并单元格和取消合并
ws.merge_cells("A1:C3")
ws.umerge_cells("A1:C3")
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)
22. 插入图片
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
wb = load_workbook('e:\\test.xlsx')
ws1=wb.active
img = Image('e:\\1.png')
ws1.add_image(img, 'A1')
# Save the file
wb.save("e:\\test.xlsx")
E:\>python a.py
Traceback (most recent call last):
File "a.py", line 13,
in <module>
wb.save("e:\\test.xlsx")
File "C:\Python27\lib\site-packages\openpyxl\workbook\workbook.py",
line 349,
in save
save_workbook(self, filename)
File
"C:\Python27\lib\site-packages\openpyxl\writer\excel.py", line 267,
in sa
ve_workbook
archive = ZipFile(filename,
'w', ZIP_DEFLATED, allowZip64=True)
File
"C:\Python27\lib\zipfile.py", line 756, in __init__
self.fp = open(file,
modeDict[mode])
IOError: [Errno 13] Permission denied: 'e:\\test.xlsx'
Excel没有关闭,所以报错!!!
E:\>python a.py
23. 隐藏列
ws1.column_dimensions.group('A', 'D',
hidden=True) 隐藏列
24. 生成柱形图
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import BarChart,
Reference, Series
wb = load_workbook('e:\\test.xlsx')
ws1=wb.active
wb = Workbook()
ws = wb.active
for i in range(10): #生成数据
ws.append([i])
values = Reference(ws, min_col=1,
min_row=1, max_col=1, max_row=10) #数据范围
chart = BarChart() #生成柱状图对象
chart.add_data(values) #柱状图对象用values存储数据
ws.add_chart(chart, "E15")
# Save the file
wb.save("e:\\test.xlsx")
25. 生成单元格,有样式
# -*- coding: utf-8 -*-
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.worksheet.table import Table,
TableStyleInfo
wb = Workbook()
ws = wb.active
data = [
['Apples', 10000, 5000, 8000, 6000],
['Pears', 2000, 3000, 4000,
5000],
['Bananas', 6000, 6000, 6500, 6000],
['Oranges', 500, 300,
200, 700],
]
# add column headings. NB. these must be
strings
ws.append(["Fruit",
"2011", "2012", "2013", "2014"])
for row in data:
ws.append(row)
tab = Table(displayName="Table1",
ref="A1:E5") #table指的是要使用样式的区域
# Add a default style with striped rows and
banded columns
style =
TableStyleInfo(name="TableStyleMedium9", showFirstColumn=True,
showLastColumn=True,
showRowStripes=True,
showColumnStripes=True)
tab.tableStyleInfo = style
ws.add_table(tab)
# Save the file
wb.save("e:\\test.xlsx")
26. 设置单元格中的字体
# -*- coding: utf-8 -*-
from openpyxl import Workbook
from openpyxl.styles import colors
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
a1 = ws['A1']
d4 = ws['D4']
ft = Font(color=colors.RED) # color="FFBB00",颜色编码也可以设定颜色
a1.font = ft
d4.font = ft
# If you want to change the color of a
Font, you need to reassign it::
a1.font = Font(color=colors.RED,
italic=True) # the change only affects A1
a1.value = "abc"
# Save the file
wb.save("e:\\test.xlsx")
16进制的颜色:
可以在网上查
27. 设置字体和大写
# -*- coding: utf-8 -*-
from openpyxl import Workbook
from openpyxl.styles import colors
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
a1 = ws['A1']
d4 = ws['D4']
ft = Font(color="FFBB00") # color="FFBB00",颜色编码也可以设定颜色
a1.font = ft
d4.font = ft
# If you want to change the color of a
Font, you need to reassign it::
a1.font = Font(name=u'宋体',size=28,color=colors.RED, italic=True) # the change only
affects A1
a1.value = "abc"
# Save the file
wb.save("e:\\test.xlsx")
28. 设置为粗体
# -*- coding: utf-8 -*-
from openpyxl import Workbook
from openpyxl.styles import colors
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
a1 = ws['A1']
d4 = ws['D4']
ft = Font(color="FFBB00") # color="FFBB00",颜色编码也可以设定颜色
a1.font = ft
d4.font = ft
# If you want to change the color of a
Font, you need to reassign it::
a1.font = Font(name=u'宋体',size=28,bold=True,color=colors.RED,
italic=True) # the
change only affects A1
a1.value = "abc"
# Save the file
wb.save("e:\\test.xlsx")
29. 设置成样式模板再去给单元格应用,但是不支持多个同时设置,需要的话可以通过循环
# -*- coding: utf-8 -*-
from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.styles import NamedStyle,
Font, Border, Side,PatternFill
wb = Workbook()
ws = wb.active
highlight =
NamedStyle(name="highlight")
highlight.font = Font(bold=True,
size=20,color= "ff0100")
highlight.fill =
PatternFill("solid", fgColor="DDDDDD")
bd = Side(style='thick', color="000000") #边框颜色及粗细
highlight.border = Border(left=bd, top=bd,
right=bd, bottom=bd) #边框
上下左右
print dir(ws["A1"])
ws["A1"].style =highlight #设置单元格样式
# Save the file
wb.save("e:\\test.xlsx")
30. 常用的样式和属性设置
# -*- coding: utf-8 -*-
from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.styles import NamedStyle, Font, Border, Side,PatternFill
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
wb = Workbook()
ws = wb.active
ft = Font(name=u'微软雅黑',
size=11,
bold=False,
italic=False,
vertAlign=None,
underline='none',
strike=False,
color='FF000000')
fill = PatternFill(fill_type="solid",
start_color='FFEEFFFF',
end_color='FF001100')
#边框可以选择的值为:'hair', 'medium', 'dashDot', 'dotted', 'mediumDashDot', 'dashed', 'mediumDashed', 'mediumDashDotDot', 'dashDotDot', 'slantDashDot', 'double', 'thick', 'thin']
#diagonal 表示对角线
bd = Border(left=Side(border_style="thin",
color='FF001000'),
right=Side(border_style="thin",
color='FF110000'),
top=Side(border_style="thin",
color='FF110000'),
bottom=Side(border_style="thin",
color='FF110000'),
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='FF110000')
)
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)
ws["B5"].font = ft
ws["B5"].fill =fill
ws["B5"].border = bd
ws["B5"].alignment = alignment
ws["B5"].number_format = number_format
ws["B5"].value ="glory road"
# Save the file
wb.save("e:\\sample.xlsx")
python-通过openpy操作excel的更多相关文章
- 转 Python - openpyxl 读写操作Excel
Python - openpyxl 读写操作Excel openpyxl特点 openpyxl(可读写excel表)专门处理Excel2007及以上版本产生的xlsx文件,xls和xlsx之间 ...
- python用openpyxl操作excel
python操作excel方法 1)自身有Win32 COM操作office但讲不清楚,可能不支持夸平台,linux是否能用不清楚,其他有专业处理模块,如下 2)xlrd:(读excel)表,xlrd ...
- python通过openpyxl操作excel
python 对Excel操作常用的主要有xlwt.xlrd.openpyxl ,前者xlwt主要适合于对后缀为xls比较进行写入,而openpyxl主要是针对于Excel 2007 以上版本进行操作 ...
- 09 python学习笔记-操作excel(九)
python操作excel使用xlrd.xlwt和xlutils模块,xlrd模块是读取excel的,xlwt模块是写excel的,xlutils是用来修改excel的.这几个模块可以使用pip安装, ...
- 用python库openpyxl操作excel,从源excel表中提取信息复制到目标excel表中
现代生活中,我们很难不与excel表打交道,excel表有着易学易用的优点,只是当表中数据量很大,我们又需要从其他表册中复制粘贴一些数据(比如身份证号)的时候,我们会越来越倦怠,毕竟我们不是机器,没法 ...
- Python - openpyxl 读写操作Excel
openpyxl特点 openpyxl(可读写excel表)专门处理Excel2007及以上版本产生的xlsx文件,xls和xlsx之间转换容易 注意:如果文字编码是“gb2312” 读取后就会显 ...
- python使用xlrd操作Excel文件
一.xlrd读取Excel文件 用xlrd进行读取比较方便,流程和平常手动操作Excel一样,打开工作簿(Workbook),选择工作表(sheets),然后操作单元格(cell). 例子:要打开当前 ...
- python使用xlrd 操作Excel读写
此文章非本人 一.安装xlrd模块 到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境. 二.使用介绍 1.导入模块 i ...
- Python使用openpyxl操作excel表格
前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取 ht ...
随机推荐
- jq或zp监听input的value改变问题
$(document).on('input propertychange','#citySelectorValue',function () { alert("s"); } 以上J ...
- Java方式配置Spring
概述 本文主要讲的是如何使用Java Bean来配置Spring,而不是用xml来配置Spring. 本文主要是代码,需要注意的都在注释里面. 代码打包下载地址(注:项目使用Maven构建) Java ...
- 代码中看见一共8个变量参数{SEO,0,0,0,0,0,0,0} 解读!{Top,0,0,0,0,0,0,Top}{Nav,0,0,0,0,0,0,Nav}
代码中看见{SEO,0,0,0,0,0,0,0}{Top,0,0,0,0,0,0,Top}{Nav,0,0,0,0,0,0,Nav}解读! 举个例子: {GetNew,977,0,23,500,0,0 ...
- deepin15.2无线网无法使用
原文链接:https://bbs.deepin.org/forum.php?mod=viewthread&tid=40276&highlight=%E6%97%A0%E7%BA%BF% ...
- ES-Mac OS环境搭建-kibana
简介 Kibana是一个为ElasticSearch 提供的数据分析的 Web 接口.可使用它对日志进行高效的搜索.可视化.分析等各种操作. 下载 打开elasticseach官网,单击downloa ...
- 【学习笔记】六:面向对象的程序设计——理解JS中的对象属性、创建对象、JS中的继承
ES中没有类的概念,这也使其对象和其他语言中的对象有所不同,ES中定义对象为:“无序属性的集合,其属性包含基本值.对象或者函数”.现在常用的创建单个对象的方法为对象字面量形式.在常见多个对象时,使用工 ...
- 在PaaS上开发Web、移动应用(2)
在PaaS上开发Web.移动应用(2) PaaS学习笔记目录 PaaS基础学习(1) 在PaaS上开发Web.移动应用(2) PaaS优点与限制(3) 6. 巨型代码,是指持续不断地向一个应用程序添加 ...
- uvm_object ——太极
无极生太极——无名天地之始 太极生两仪——有名万物之母 文件: $UVM_HOME/src/base/uvm_object.svh 类: uvm_object The uvm_object cla ...
- 如何使用KeyChain保存和获取UDID
本文是iOS7系列文章第一篇文章,主要介绍使用KeyChain保存和获取APP数据,解决iOS7上获取不变UDID的问题.并给出一个获取UDID的工具类,使用方便,只需要替换两个地方即可. 一.iOS ...
- win7 ghost 纯净版最新系统下载
这个系统是WIN7系统GHOST版装机旗舰版 SP1,更新了系统补丁到2016-02(可通过微软漏洞扫描和卫士漏洞扫描),升级Internet Explorer为IE9,增加数款驱动的支持,支持最新的 ...