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
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>), (