Python_Openpyxl
1. Install
pip install openpyxl
2. Open the file
from openpyxl import Workbook
# 实例化
wb = Workbook()
# 激活 worksheet
ws = wb.active
② Open an existing
>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('文件名称.xlsx')
3. Data Storage
# 方式一:数据可以直接分配到单元格中(可以输入公式)
ws['A1'] = 42
# 方式二:可以附加行,从第一列开始附加(从最下方空白处,最左开始)(可以输入多行)
ws.append([1, 2, 3])
# 方式三:Python 类型会被自动转换
ws['A3'] = datetime.datetime.now().strftime("%Y-%m-%d")
4. Create a table (sheet)
# 方式一:插入到最后(default)
>>> ws1 = wb.create_sheet("Mysheet")
# 方式二:插入到最开始的位置
>>> ws2 = wb.create_sheet("Mysheet", 0)
5. Selection Table (Sheet)
# Sheet name may be used as the key index
>>> ws3 = wb [ "New the Title"]
>>> WS4 = wb.get_sheet_by_name ( "New the Title")
>>> WS IS ws3 IS WS4
True
6. Check the table name (sheet)
# 显示所有表名
>>> print(wb.sheetnames)
['Sheet2', 'New Title', 'Sheet1']
# 遍历所有表
>>> for sheet in wb:
... print(sheet.title)
7. Access cell (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)
# 通过切片
>>> 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. Save Data
>>> wb.save('文件名称.xlsx')
9. Other
① change the color of the button label sheet
ws.sheet_properties.tabColor = "1072BA"
② get the maximum line, maximum column
# 获得最大列和最大行
print(sheet.max_row)
print(sheet.max_column)
③ obtain each row, each column
sheet.rows
Is a generator, which is data for each row, each row consists of a tuple package.sheet.columns
Similarly, but there is and each tuple is the cell of each column.
Because row #, is returned A1, B1, C1 in this order
for Row in sheet.rows:
for in Row Cell:
Print (Cell.Value)
# A1, A2, A3这样的顺序
for column in sheet.columns:
for cell in column:
print(cell.value)
④ obtained digital letters, numbers obtained alphabetical
from openpyxl.utils import get_column_letter, column_index_from_string
# 根据列的数字返回字母
print(get_column_letter(2)) # B
# 根据字母返回列的数字
print(column_index_from_string('D')) # 4
# 方式一
wb.remove(sheet)
# 方式二
del wb[sheet]
⑥ substitution matrix (row → column)
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)]
10. Set cell style
from openpyxl.styles import Font, colors, Alignment
- The following code is specified
等线24号
,加粗斜体
the font color红色
. The direct use of cellfont
attributes, assign Font object to it.
bold_itatic_24_font = Font(name='等线', size=24, italic=True, color=colors.RED, bold=True)
sheet['A1'].font = bold_itatic_24_font
- It is the direct use of cell attributes
aligment
, here designated centered vertically and centered horizontally. In addition to center, can also be usedright、left
, etc. parameters.
# 设置B1中的数据垂直居中和水平居中
sheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
④ set the row height and the column width
# 第2行行高
sheet.row_dimensions[2].height = 40
# C列列宽
sheet.column_dimensions['C'].width = 30
- The so-called merge cells, that is, the upper-left cell of the merged area as a reference, so that it covers the other cells known as a large cell.
- Instead, this value will split cells large cell returns to the original position of the top left corner.
# 合并单元格, 往左上角写入数据即可
sheet.merge_cells('B1:G1') # 合并一行中的几个单元格
sheet.merge_cells('A1:C3') # 合并一个矩形区域中的单元格
- After the merger can only write data to the upper left corner, which is in the range: the coordinates of the left.
- If you want to merge these cells have the data, it will only retain the upper left corner of the data, while others are discarded. In other words before the writing data is not combined if the upper left corner, no data is merged cell.
- The following code is split cells. After the split, the value back to the A1 position.
sheet.unmerge_cells('A1:C3')
The last example
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)
This is mainly finishing two big God blog of
one of the original address: https://blog.csdn.net/fanlei_lianjia/article/details/78225857
another'm sorry I forgot the address. . . . (If someone tells me I'm connected, will be corrected)