python openpyxl

1、python 新建execl,写入数据:

-- coding: utf-8 --

from openpyxl import Workbook
wb = Workbook() #创建文件对象

grab the active worksheet

ws = wb.active #获取第一个sheet

Data can be assigned directly to cells

ws['A1'] = 42 #写入数字
ws['B1'] = "你好"+"automation test" #写入中文(unicode中文也可)

Rows can also be appended

ws.append([1, 2, 3]) #写入多个单元格

Python types will automatically be converted

import datetime
import time
ws['A2'] = datetime.datetime.now() #写入一个当前时间

写入一个自定义的时间格式

ws['A3'] =time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年',m='月',d='日',h='时',f='分',s='秒')

Save the file

wb.save("sample.xlsx")

2、操作表单:

-- coding: utf-8 --

from openpyxl import Workbook
wb = Workbook()

ws1 = wb.create_sheet("Mysheet") #创建一个sheet
ws1.title = "New Title" #设定一个sheet的名字
ws2 = wb.create_sheet("Mysheet", 0) #设定sheet的插入位置 默认插在后面
ws2.title = u"你好" #设定一个sheet的名字 必须是Unicode

ws1.sheet_properties.tabColor = "1072BA" #设定sheet的标签的背景颜色

获取某个sheet对象

print(wb.get_sheet_by_name("你好"))
print(wb["New Title" ])

获取全部sheet 的名字,遍历sheet名字

print(wb.sheetnames)
for sheet_name in wb.sheetnames:
print(sheet_name)

print(""50)

for sheet in wb:
print(sheet.title)

复制一个sheet

wb["New Title" ]["A1"]="zeke"
source = wb["New Title" ]
target = wb.copy_worksheet(source)

w3 = wb.copy_worksheet(wb['new title'])

ws3.title = 'new2'

wb.copy_worksheet(wb['new title']).title = 'hello'

Save the file

wb.save("sample1.xlsx")

3、操作单元格:

-- coding: utf-8 --

from openpyxl import Workbook
wb = Workbook()
ws1 = wb.create_sheet("Mysheet") #创建一个sheet

ws1["A1"]=123.11
ws1["B2"]="你好"
d = ws1.cell(row=4, column=2, value=10)

print ws1["A1"].value
print ws1["B2"].value
print d.value

Save the file

wb.save("e:\sample.xlsx")

4、多行操作、多列操作,wt["A:C"]

-- coding: utf-8 --

from openpyxl import Workbook
wb = Workbook()

ws1 = wb.create_sheet("Mysheet") #创建一个sheet

ws1["A1"]=1
ws1["A2"]=2
ws1["A3"]=3

ws1["B1"]=4
ws1["B2"]=5
ws1["B3"]=6

ws1["C1"]=7
ws1["C2"]=8
ws1["C3"]=9

操作单列

print ws1["A"]
for cell in ws1["A"]:
print cell.value

操作多列,获取每一个值

print ws1["A:C"]
for column in ws1["A:C"]:
for cell in column:
print cell.value

操作多行

row_range = ws1[1:3]
print row_range
for row in row_range:
for cell in row:
print cell.value

print ""50
for row in ws1.iter_rows(min_row=1, min_col=1, max_col=3, max_row=3):
for cell in row:
print cell.value

获取所有行

print ws1.rows
for row in ws1.rows:
print row

print ""50

获取所有列

print ws1.columns
for col in ws1.columns:
print col

wb.save("e:\sample.xlsx")

5、wb.guess_type =False ,显示原始格式:

-- coding: utf-8 --

from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('e:\sample.xlsx')
wb.guess_types = False
ws=wb.active
ws["D1"]="12%"
print ws["D1"].value
wb.save("e:\sample.xlsx")

结果会打印百分数

6、load_workbook

-- coding: utf-8 --

from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('e:\sample.xlsx')
wb.guess_types = True #猜测格式类型
ws=wb.active
ws["D1"]="12%"
print ws["D1"].value

Save the file

wb.save("e:\sample.xlsx")

注意如果原文件有一些图片或者图标,则保存的时候可能会导致图片丢失

7、number_format单元格类型

-- coding: utf-8 --

from openpyxl import Workbook
from openpyxl import load_workbook
import datetime
wb = load_workbook('e:\sample.xlsx')

ws=wb.active
wb.guess_types = True

ws["A1"]=datetime.datetime(2010, 7, 21)
print ws["A1"].number_format

ws["A2"]="12%"
print ws["A2"].number_format

ws["A3"]= 1.1
print ws["A4"].number_format

ws["A4"]= "中国"
print ws["A5"].number_format

Save the file

wb.save("e:\sample.xlsx")
执行结果:
yyyy-mm-dd h:mm:ss
0%
General
General

如果是常规,显示general,如果是数字,显示'0.00_ ',如果是百分数显示0%

数字需要在Excel中设置数字类型,直接写入的数字是常规类型

8、使用公式:

-- coding: utf-8 --

from openpyxl import Workbook
from openpyxl import load_workbook

wb = load_workbook('e:\sample.xlsx')
ws1=wb.active

ws1["A1"]=1
ws1["A2"]=2
ws1["A3"]=3

ws1["A4"] = "=SUM(1, 1)"
ws1["A5"] = "=SUM(A1:A3)"

print ws1["A4"].value #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值
print ws1["A5"].value #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值

Save the file

wb.save("e:\sample.xlsx")

9、合并单元格merge_cells,unmerge_cells

-- coding: utf-8 --

from openpyxl import Workbook
from openpyxl import load_workbook

wb = load_workbook('e:\sample.xlsx')
ws1=wb.active

ws.merge_cells('A2:D2')
ws.unmerge_cells('A2:D2') #合并后的单元格,脚本单独执行拆分操作会报错,需要重新执行合并操作再拆分

or equivalently

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)

Save the file

wb.save("e:\sample.xlsx")

10、addImage插入图片

-- coding: utf-8 --

from openpyxl import load_workbook
from openpyxl.drawing.image import Image

wb = load_workbook('e:\sample.xlsx')
ws1=wb.active

img = Image('e:\1.png')
ws1.add_image(img, 'A1')

Save the file

wb.save("e:\sample.xlsx")

11、hidden 隐藏列

-- coding: utf-8 --

from openpyxl import load_workbook
from openpyxl.drawing.image import Image

wb = load_workbook('e:\sample.xlsx')
ws1=wb.active

ws1.column_dimensions.group('A', 'D', hidden=True) #隐藏a到d列范围内的列

ws1.row_dimensions 无group方法

Save the file

wb.save("e:\sample.xlsx")

12、BarChart画柱状图
12、 画一个柱状图

-- coding: utf-8 --

from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference, Series

wb = load_workbook('e:\sample.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)
ws.add_chart(chart, "E15")

Save the file

wb.save("e:\sample.xlsx")

13、画饼图:piechart

-- coding: utf-8 --

from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import (PieChart , ProjectedPieChart, Reference)
from openpyxl.chart.series import DataPoint

data = [
['Pie', 'Sold'],
['Apple', 50],
['Cherry', 30],
['Pumpkin', 10],
['Chocolate', 40],
]

wb = Workbook()
ws = wb.active

for row in data:
ws.append(row)

pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"

Cut the first slice out of the pie

slice = DataPoint(idx=0, explosion=20)
pie.series[0].data_points = [slice]

ws.add_chart(pie, "D1")

ws = wb.create_sheet(title="Projection")

data = [
['Page', 'Views'],
['Search', 95],
['Products', 4],
['Offers', 0.5],
['Sales', 0.5],
]

for row in data:
ws.append(row)

projected_pie = ProjectedPieChart()
projected_pie.type = "pie"
projected_pie.splitType = "val" # split by value
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
projected_pie.add_data(data, titles_from_data=True)
projected_pie.set_categories(labels)

ws.add_chart(projected_pie, "A10")

from copy import deepcopy
projected_bar = deepcopy(projected_pie)
projected_bar.type = "bar"
projected_bar.splitType = 'pos' # split by position

ws.add_chart(projected_bar, "A27")

Save the file

wb.save("e:\sample.xlsx")

14 划分表格区域,并设定表格样式

-- 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")

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:\sample.xlsx")

15、给单元格设定字体样式:

-- 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::

italic 倾斜字体

a1.font = Font(color=colors.RED, italic=True) # the change only affects A1
a1.value = "abc"

Save the file

wb.save("e:\sample.xlsx")

16、设定字体和大小

-- 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']
a1.value = "abc"

from openpyxl.styles import Font
from copy import copy

ft1 = Font(name=u'宋体', size=14)
ft2 = copy(ft1) #复制字体对象
ft2.name = "Tahoma"

print ft1.name
print ft2.name
print ft2.size # copied from the

a1.font = ft1

Save the file

wb.save("e:\sample.xlsx")

17、给整行和整列设定字体

-- coding: utf-8 --

from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active

col = ws.column_dimensions['A']
col.font = Font(bold=True) #将A列设定为粗体
row = ws.row_dimensions[1]
row.font = Font(underline="single") #将第一行设定为下划线格式

Save the file

wb.save("e:\sample.xlsx")

18、给单元格设定背景和边框

-- 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:\sample.xlsx")

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,240评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,328评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,182评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,121评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,135评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,093评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,013评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,854评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,295评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,513评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,678评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,398评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,989评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,636评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,801评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,657评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,558评论 2 352

推荐阅读更多精彩内容

  • 一、写一个excel # -*- coding: utf-8 -*- import locale from ope...
    公子小白123阅读 394评论 0 2
  • 最近在网上爬取奥运项目资料,并写入Excel中。在写到Excel中是用到了OpenPyXL,翻译了一部分自己用到的...
    LeeLom阅读 199,810评论 7 78
  • openpyxl模块安装 以管理员模式运行 CMD 输入:pip install openpyxl 稍等会自动安装...
    Python有毒阅读 8,929评论 4 5
  • 在昨天早上,我的腿疼了,体育课都上不了,就算上了我也跑不了,因为我的腿必须是弯的,直不起来,如果直起来,腿就会非常...
    孙浩洋阅读 241评论 2 5
  • 夜微凉,灯微暗,等一场雪,却飘来了雨。 然而时光是一道迷幻绚丽而最终面目可憎的阴影,所有美丽的预言都会成为平...
    知道一点点阅读 547评论 0 4