Python_Openpyxl 淺談(最全總結 足夠初次使用)


https://blog.csdn.net/weixin_43094965/article/details/82226263?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

 

https://blog.csdn.net/u014597198/article/details/83104653

 

https://www.cnblogs.com/lgqboke/p/10907076.html

 

https://blog.csdn.net/weixin_33854644/article/details/93277706

https://blog.csdn.net/qq_32502511/article/details/56496195?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

 

https://blog.csdn.net/qq_42897441/article/details/89708168?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-1

Python_Openpyxl

1. 安裝

pip install openpyxl 
  • 1
  • 1

2. 打開文件

① 創建

from openpyxl import Workbook # 實例化 wb = Workbook() # 激活 worksheet ws = wb.active 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

② 打開已有

>>> from openpyxl import load_workbook >>> wb2 = load_workbook('文件名稱.xlsx') 
  • 1
  • 2
  • 1
  • 2

3. 儲存數據

# 方式一:數據可以直接分配到單元格中(可以輸入公式) ws['A1'] = 42 # 方式二:可以附加行,從第一列開始附加(從最下方空白處,最左開始)(可以輸入多行) ws.append([1, 2, 3]) # 方式三:Python 類型會被自動轉換 ws['A3'] = datetime.datetime.now().strftime("%Y-%m-%d") 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4. 創建表(sheet)

# 方式一:插入到最后(default) >>> ws1 = wb.create_sheet("Mysheet") # 方式二:插入到最開始的位置 >>> ws2 = wb.create_sheet("Mysheet", 0) 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

5. 選擇表(sheet)

# sheet 名稱可以作為 key 進行索引 >>> ws3 = wb["New Title"] >>> ws4 = wb.get_sheet_by_name("New Title") >>> ws is ws3 is ws4 True 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

6. 查看表名(sheet)

# 顯示所有表名 >>> print(wb.sheetnames) ['Sheet2', 'New Title', 'Sheet1'] # 遍歷所有表 >>> for sheet in wb: ... print(sheet.title) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

7. 訪問單元格(call)

① 單一單元格訪問

# 方法一 >>> c = ws['A4'] # 方法二:row 行;column 列 >>> d = ws.cell(row=4, column=2, value=10) # 方法三:只要訪問就創建 >>> for i in range(1,101): ... for j in range(1,101): ... ws.cell(row=i, column=j) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

② 多單元格訪問

# 通過切片 >>> 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>)) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

8. 保存數據

>>> wb.save('文件名稱.xlsx') 
  • 1
  • 1

9. 其他

① 改變 sheet 標簽按鈕顏色

ws.sheet_properties.tabColor = "1072BA" 
  • 1
  • 1

② 獲取最大行,最大列

# 獲得最大列和最大行 print(sheet.max_row) print(sheet.max_column) 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

③ 獲取每一行,每一列

  • sheet.rows為生成器, 里面是每一行的數據,每一行又由一個tuple包裹。
  • sheet.columns類似,不過里面是每個tuple是每一列的單元格。
# 因為按行,所以返回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) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

④ 根據數字得到字母,根據字母得到數字

from openpyxl.utils import get_column_letter, column_index_from_string # 根據列的數字返回字母 print(get_column_letter(2)) # B # 根據字母返回列的數字 print(column_index_from_string('D')) # 4 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

⑤ 刪除工作表

# 方式一 wb.remove(sheet) # 方式二 del wb[sheet] 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

⑥ 矩陣置換(行 → 列)

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)] # 注意 方法會舍棄缺少數據的列(行) rows = [ ['Number', 'data1', 'data2'], [2, 40 ], # 這里少一個數據 [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)] 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

10. 設置單元格風格

① 需要導入的類

from openpyxl.styles import Font, colors, Alignment 
  • 1
  • 1

② 字體

  • 下面的代碼指定了等線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 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

③ 對齊方式

  • 也是直接使用cell的屬性aligment,這里指定垂直居中和水平居中。除了center,還可以使用right、left等等參數。
# 設置B1中的數據垂直居中和水平居中 sheet['B1'].alignment = Alignment(horizontal='center', vertical='center') 
  • 1
  • 2
  • 1
  • 2

④ 設置行高和列寬

# 第2行行高 sheet.row_dimensions[2].height = 40 # C列列寬 sheet.column_dimensions['C'].width = 30 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

⑤ 合並和拆分單元格

  • 所謂合並單元格,即以合並區域的左上角的那個單元格為基准,覆蓋其他單元格使之稱為一個大的單元格。
  • 相反,拆分單元格后將這個大單元格的值返回到原來的左上角位置。
# 合並單元格, 往左上角寫入數據即可 sheet.merge_cells('B1:G1') # 合並一行中的幾個單元格 sheet.merge_cells('A1:C3') # 合並一個矩形區域中的單元格 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
  • 合並后只可以往左上角寫入數據,也就是區間中:左邊的坐標。
  • 如果這些要合並的單元格都有數據,只會保留左上角的數據,其他則丟棄。換句話說若合並前不是在左上角寫入數據,合並后單元格中不會有數據。
  • 以下是拆分單元格的代碼。拆分后,值回到A1位置。
sheet.unmerge_cells('A1:C3') 
  • 1
  • 1

最后舉個例子

import datetime from random import choice from time import time from openpyxl import load_workbook from openpyxl.utils import get_column_letter # 設置文件 mingc addr = "openpyxl.xlsx" # 打開文件 wb = load_workbook(addr) # 創建一張新表 ws = wb.create_sheet() # 第一行輸入 ws.append(['TIME', 'TITLE', 'A-Z']) # 輸入內容(500行數據) 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 # 把上面寫入內容打印在控制台 for j in ws.rows: # we.rows 獲取每一行數據 for n in j: print(n.value, end="\t") # n.value 獲取單元格的值 print() # 保存,save(必須要寫文件名(絕對地址)默認 py 同級目錄下,只支持 xlsx 格式) wb.save(addr)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM