1. 安裝
pip install openpyxl
2. 打開文件
① 創(chuàng)建
from openpyxl import Workbook
# 實(shí)例化
wb = Workbook()
# 激活 worksheet
ws = wb.active
② 打開已有
>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('文件名稱.xlsx')
3. 儲存數(shù)據(jù)
# 方式一:數(shù)據(jù)可以直接分配到單元格中(可以輸入公式)
ws['A1'] = 42
# 方式二:可以附加行,從第一列開始附加(從最下方空白處,最左開始)(可以輸入多行)
ws.append([1, 2, 3])
# 方式三:Python 類型會被自動轉(zhuǎn)換
ws['A3'] = datetime.datetime.now().strftime("%Y-%m-%d")
4. 創(chuàng)建表(sheet)
# 方式一:插入到最后(default)
>>> ws1 = wb.create_sheet("Mysheet")
# 方式二:插入到最開始的位置
>>> ws2 = wb.create_sheet("Mysheet", 0)
5. 選擇表(sheet)
# sheet 名稱可以作為 key 進(jìn)行索引
>>> ws3 = wb["New Title"]
>>> ws4 = wb.get_sheet_by_name("New Title")
>>> ws is ws3 is ws4
True
6. 查看表名(sheet)
# 顯示所有表名
>>> print(wb.sheetnames)
['Sheet2', 'New Title', 'Sheet1']
# 遍歷所有表
>>> for sheet in wb:
... print(sheet.title)
7. 訪問單元格(call)
① 單一單元格訪問
# 方法一
>>> c = ws['A4']
# 方法二:row 行;column 列
>>> d = ws.cell(row=4, column=2, value=10)
# 方法三:只要訪問就創(chuàng)建
>>> for i in range(1,101):
... for j in range(1,101):
... ws.cell(row=i, column=j)
② 多單元格訪問
# 通過切片
>>> cell_range = ws['A1':'C2']
# 通過行(列)
>>> colC = ws['C']
>>> col_range = ws['C:D']
>>> row10 = ws[10]
>>> row_range = ws[5:10]
# 通過指定范圍(行 → 行)
>>> 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>
# 通過指定范圍(列 → 列)
>>> 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>
# 遍歷所有 方法一
>>> 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.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
(<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))
# 遍歷所有 方法二
>>> tuple(ws.columns)
((<Cell Sheet.A1>,
<Cell Sheet.A2>,
<Cell Sheet.A3>,
...
<Cell Sheet.B7>,
<Cell Sheet.B8>,
<Cell Sheet.B9>),
(<Cell Sheet.C1>,
...
<Cell Sheet.C8>,
<Cell Sheet.C9>))
8. 保存數(shù)據(jù)
>>> wb.save('文件名稱.xlsx')
9. 其他
① 改變 sheet 標(biāo)簽按鈕顏色
ws.sheet_properties.tabColor = "1072BA"
② 獲取最大行,最大列
# 獲得最大列和最大行
print(sheet.max_row)
print(sheet.max_column)
③ 獲取每一行,每一列
sheet.rows 為生成器, 里面是每一行的數(shù)據(jù),每一行又由一個tuple包裹。
sheet.columns 類似,不過里面是每個tuple是每一列的單元格。
# 因?yàn)榘葱?,所以返回A1, B1, C1這樣的順序
for row in sheet.rows:
for cell in row:
print(cell.value)
# A1, A2, A3這樣的順序
for column in sheet.columns:
for cell in column:
print(cell.value)
④ 根據(jù)數(shù)字得到字母,根據(jù)字母得到數(shù)字
from openpyxl.utils import get_column_letter, column_index_from_string
# 根據(jù)列的數(shù)字返回字母
print(get_column_letter(2)) # B
# 根據(jù)字母返回列的數(shù)字
print(column_index_from_string('D')) # 4
⑤ 刪除工作表
# 方式一
wb.remove(sheet)
# 方式二
del wb[sheet]
⑥ 矩陣置換(行 → 列)
rows = [
['Number', 'data1', 'data2'],
[2, 40, 30],
[3, 40, 25],
[4, 50, 30],
[5, 30, 10],
[6, 25, 5],
[7, 50, 10]]
list(zip(*rows))
# out
[('Number', 2, 3, 4, 5, 6, 7),
('data1', 40, 40, 50, 30, 25, 50),
('data2', 30, 25, 30, 10, 5, 10)]
# 注意 方法會舍棄缺少數(shù)據(jù)的列(行)
rows = [
['Number', 'data1', 'data2'],
[2, 40 ], # 這里少一個數(shù)據(jù)
[3, 40, 25],
[4, 50, 30],
[5, 30, 10],
[6, 25, 5],
[7, 50, 10],
]
# out
[('Number', 2, 3, 4, 5, 6, 7), ('data1', 40, 40, 50, 30, 25, 50)]
10. 設(shè)置單元格風(fēng)格
① 需要導(dǎo)入的類
from openpyxl.styles import Font, colors, Alignment
② 字體
- 下面的代碼指定了
等線24號 ,加粗斜體 ,字體顏色紅色 。直接使用cell的font 屬性,將Font對象賦值給它。
bold_itatic_24_font = Font(name='等線', size=24, italic=True, color=colors.RED, bold=True)
sheet['A1'].font = bold_itatic_24_font
③ 對齊方式
- 也是直接使用cell的屬性
aligment ,這里指定垂直居中和水平居中。除了center,還可以使用right、left 等等參數(shù)。
# 設(shè)置B1中的數(shù)據(jù)垂直居中和水平居中
sheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
④ 設(shè)置行高和列寬
# 第2行行高
sheet.row_dimensions[2].height = 40
# C列列寬
sheet.column_dimensions['C'].width = 30
⑤ 合并和拆分單元格
- 所謂合并單元格,即以合并區(qū)域的左上角的那個單元格為基準(zhǔn),覆蓋其他單元格使之稱為一個大的單元格。
- 相反,拆分單元格后將這個大單元格的值返回到原來的左上角位置。
# 合并單元格, 往左上角寫入數(shù)據(jù)即可
sheet.merge_cells('B1:G1') # 合并一行中的幾個單元格
sheet.merge_cells('A1:C3') # 合并一個矩形區(qū)域中的單元格
- 合并后只可以往左上角寫入數(shù)據(jù),也就是區(qū)間中:左邊的坐標(biāo)。
- 如果這些要合并的單元格都有數(shù)據(jù),只會保留左上角的數(shù)據(jù),其他則丟棄。換句話說若合并前不是在左上角寫入數(shù)據(jù),合并后單元格中不會有數(shù)據(jù)。
- 以下是拆分單元格的代碼。拆分后,值回到A1位置。
sheet.unmerge_cells('A1:C3')
最后舉個例子
import datetime
from random import choice
from time import time
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
# 設(shè)置文件 mingc
addr = "openpyxl.xlsx"
# 打開文件
wb = load_workbook(addr)
# 創(chuàng)建一張新表
ws = wb.create_sheet()
# 第一行輸入
ws.append(['TIME', 'TITLE', 'A-Z'])
# 輸入內(nèi)容(500行數(shù)據(jù))
for i in range(500):
TIME = datetime.datetime.now().strftime("%H:%M:%S")
TITLE = str(time())
A_Z = get_column_letter(choice(range(1, 50)))
ws.append([TIME, TITLE, A_Z])
# 獲取最大行
row_max = ws.max_row
# 獲取最大列
con_max = ws.max_column
# 把上面寫入內(nèi)容打印在控制臺
for j in ws.rows: # we.rows 獲取每一行數(shù)據(jù)
for n in j:
print(n.value, end="\t") # n.value 獲取單元格的值
print()
# 保存,save(必須要寫文件名(絕對地址)默認(rèn) py 同級目錄下,只支持 xlsx 格式)
wb.save(addr)
這里主要是兩位大神博客的整理
其中一個原地址:https://blog.csdn.net/fanlei_lianjia/article/details/78225857
另一個很抱歉忘了地址了。。。。(如果有人告訴我我連接,將更正)
|