原始表结构与内容如下:
# 导入模块
from openpyxl import Workbook, load_workbook
# 加载工作表
wb = load_workbook('MyExcel.xlsx')
# 加载当前激活的工作簿
ws1 = wb.active
# 加载指定名字的工作簿
ws2 = wb['Sheet1']
# 获取单元格的方式
print(ws1['A1'].value) # name
# 修改内容
ws1['B2'].value = 100 # 99 -> 100
# 查看工作簿
print(wb.sheetnames) # ['Grades', 'Sheet1', 'Sheet2']
# 添加工作簿,第一个参数为工作簿名,第二个参数为工作簿列表里的位置(索引)
wb.create_sheet('Sheet3', 3)
# 保存内容
wb.save('MyExcel.xlsx') # 参数为文件名
from openpyxl import load_workbook
wb = load_workbook('MyExcel.xlsx')
ws = wb['Sheet1']
# 添加数据
ws.append(['Name', 'Age', 'Gender', 'Department'])
ws.append(['Richie', '21', 'Male', 'Student'])
ws.append(['Taylor', '34', 'Female', 'Singer'])
ws.append(['Mike', '32', 'Male', 'Teacher'])
wb.save('MyExcel.xlsx')
效果如下:
# 导入模块
from openpyxl import Workbook,load_workbook
from openpyxl.utils import get_column_letter
# 加载工作表、工作簿
wb = load_workbook('MyExcel.xlsx')
ws = wb['Grades']
# 循环遍历数据
for row in ws.rows:
for data in row:
print(data.value)
-------------------------------------
name
math
science
english
gym
Richie
99
87
84
89
Taylor
87
67
99
56
Mike
42
67
87
76
Jack
94
78
76
67
Jane
78
34
98
45
合并单元格代码如下:
# 导入模块
from openpyxl import Workbook,load_workbook
from openpyxl.utils import get_column_letter
# 加载工作表、工作簿
wb = load_workbook('MyExcel.xlsx')
ws = wb['Sheet2']
# 合并单元格
ws.merge_cells('A1:D1')
ws.merge_cells('A2:D4')
# 保存
wb.save('MyExcel.xlsx')
效果如下:
取消合并单元格代码如下:
# 导入模块
from openpyxl import Workbook,load_workbook
from openpyxl.utils import get_column_letter
# 加载工作表、工作簿
wb = load_workbook('MyExcel.xlsx')
ws = wb['Sheet2']
# 取消合并单元格
ws.unmerge_cells('A1:D1')
ws.unmerge_cells('A2:D4')
# 保存
wb.save('MyExcel.xlsx')
效果如下;
添加行代码如下:
# 导入模块
from openpyxl import Workbook,load_workbook
from openpyxl.utils import get_column_letter
# 加载工作表、工作簿
wb = load_workbook('MyExcel.xlsx')
ws = wb['Grades']
# 添加行,同理添加列 方法为insert_cols(数字)
ws.insert_rows(1)
ws.insert_rows(1)
# 保存
wb.save('MyExcel.xlsx')
效果如下:
删除行代码如下:
# 导入模块
from openpyxl import Workbook,load_workbook
from openpyxl.utils import get_column_letter
# 加载工作表、工作簿
wb = load_workbook('MyExcel.xlsx')
ws = wb['Grades']
# 删除行,同理删除列 方法为delete_cols(数字)
ws.delete_rows(1)
ws.delete_rows(1)
# 保存
wb.save('MyExcel.xlsx')
效果如下:
代码如下:
# 导入模块
from openpyxl import Workbook,load_workbook
from openpyxl.utils import get_column_letter
# 加载工作表、工作簿
wb = load_workbook('MyExcel.xlsx')
ws = wb['Grades']
# 移动指定范围单元格,第一个参数为一个范围的单元格,rows正数为向下,cols正数为向右
ws.move_range('A5:E6', rows=2, cols=2)
# 保存
wb.save('MyExcel.xlsx')
效果如下: