python操做Excel模塊openpyxl

一、 安裝

pip install openpyxl安全

想要在文件中插入圖片文件,須要安裝pillow安裝文件PIL-fork-1.1.7.win-amd64-py2.7.exeapp

 

· font(字體類):字號、字體顏色、下劃線等ide

· fill(填充類):顏色等字體

· border(邊框類):設置單元格邊框ui

· alignment(位置類):對齊方式編碼

· number_format(格式類):數據格式spa

· protection(保護類):寫保護excel

 

二、 建立一個excel 文件,並寫入不一樣類的內容

 

# -*- 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年%m月%d日 %H時%M分%S秒",time.localtime())

# Save the file
wb.save("e:\\sample.xlsx")

 

三、 建立sheet

# -*- 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(u"你好"  )
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("e:\\sample.xlsx")

 

四、 操做單元格

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

 

五、 操做批量的單元格

不管ws.rows仍是ws.iter_rows都是一個對象code

除上述兩個對象外 單行,單列都是一個元祖,多行多列是二維元祖orm

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

 

使用百分數

# -*- 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")
#結果會打印小數

 

# -*- 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")
#結果會打印百分數

 

獲取全部的行對象:

#coding=utf-8
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('e:\\sample.xlsx')
ws=wb.active
rows=[]
for row in ws.iter_rows():
            rows.append(row)
print rows   #全部行
print rows[0] #獲取第一行
print rows[0][0] #獲取第一行第一列的單元格對象
print rows[0][0].value #獲取第一行第一列的單元格對象的值
 
print rows[len(rows)-1] #獲取最後行 print rows[-1]
print rows[len(rows)-1][len(rows[0])-1] #獲取第後一行和最後一列的單元格對象
print rows[len(rows)-1][len(rows[0])-1].value #獲取第後一行和最後一列的單元格對象的值

 

獲取全部的列對象:

#coding=utf-8
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('e:\\sample.xlsx')
ws=wb.active
cols=[]
cols = []
for col in ws.iter_cols():
    cols.append(col)
 
print cols   #全部列
print cols[0]   #獲取第一列
print cols[0][0]   #獲取第一列的第一行的單元格對象
print cols[0][0].value   #獲取第一列的第一行的值
 
print "*"*30
print cols[len(cols)-1]   #獲取最後一列
print cols[len(cols)-1][len(cols[0])-1]   #獲取最後一列的最後一行的單元格對象
print cols[len(cols)-1][len(cols[0])-1].value   #獲取最後一列的最後一行的單元格對象的值

 

六、 操做已經存在文件

# -*- 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")
#注意若是原文件有一些圖片或者圖標,則保存的時候可能會致使圖片丟失

 

七、 單元格類型

 # -*- 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中設置數字類型,直接寫入的數字是常規類型

 

八、 使用公式

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

 

九、 合併單元格

# -*- 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插入一個圖片

須要先安裝Pilow,安全文件PIL-fork-1.1.7.win-amd64-py2.7.exe

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

 

十一、 隱藏單元格

# -*- 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、 畫一個柱狀圖
# -*- 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")

 

1三、 畫一個餅圖

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

 

1四、 設定一個表格區域,並設定表格的格式

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

 

19、經常使用的樣式屬性設置

# -*- 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 ="zeke"

# Save the file
wb.save("e:\\sample.xlsx")
相關文章
相關標籤/搜索