一、先安装openpyxl
openpyxl支持4种格式
.xlsx .xlsm .xltx .xltm
如果是以前的.xls老版本的格式,手动改为.xlsx
pip install openpyxl
二、使用openpyxl
2.1、查询
from openpyxl import load_workbook
workbook=load_workbook(r"D:\小学.xlsx")
2.1.1、获取Excel表格名称的三种方式
sheet = workbook["花名册"]
sheet2 = workbook.worksheets[0]
sheet3 = workbook.active
2.1.2、获取表格对应的尺寸大小
sheet.dimensions <Worksheet "学生表"> A1:C5
2.1.3、获取某个单元格的数据
sheet = workbook["花名册"]
print(sheet["B2"])
print(sheet["B2"].value)
2.1.4、cell()方法
cell=sheet.cell(row=2,column=2)
print(cell,cell.value)
print("单元格B2行数:{} 列数:{} 值:{} 坐标:{}".format(cell.row,cell.column,cell.value,cell.coordinate))
2.1.5、获取区域的数据(A1:C4)
cells=sheet["A1:C4"]
print(cells)
for i in cells:
for j in i:
print(j.value)
2.1.6、获取单行或者单列的数据-sheet[]方法 行 用数字 列 用字母
cells = sheet["4"]
for i in cells:
print (i.value)
cells = sheet["A"]
for i in cells:
print (i.value)
2.1.7、获取多行或者多列的数据-sheet[]方法 行 用数字 列 用字母
for i in sheet.iter_rows():
print (i)
for j in i:
print(j.value)
2.1.8、获取指定行列数据(注意:索引的最小值都是从1开始的)
for i in sheet.iter_rows(min_row=2,max_row=4,min_col=1,max_col=2):
print (i)
for j in i:
print(j.value)
2.1.9、按列获取表所有数据-sheet.iter_cols() (与iter_rows()用法一样)
2.1.10、sheet.rows和sheet.columns
from openpyxl import load_workbook
workbook=load_workbook(r"D:\小学.xlsx")
sheet = workbook["花名册"]
for i in sheet.rows:
print (i)
for j in i:
print(j.value)
for i in sheet.columns:
print (i)
for j in i:
print(j.value)
2.2、修改单元格里的值或者保存Excel(save时需要将表格保存,否则报错)
from openpyxl import load_workbook
filePath = r'D:\小学.xLsx'
workbook = load_workbook(filePath)
sheet = workbook["花名册"]
sheet["B2"] = '红buffer'
cell = sheet["B3"]
cell.value = '蓝buffer'
savePath = r'D:\小学2.xlsx'
workbook.save(savePath)
2.3、向表中插入行数据(append()添加在末尾)
from openpyxl import load_workbook
filePath = r'D:\小学.xlsx'
workbook = load_workbook(filePath)
sheet = workbook["花名册"]
data=[
["5","小红","女"],
["6", "小花","女"],
["7", "夏洛","男"]
]
for row in data:
sheet.append(row)
workbook.save(filePath)
2.4、插入空行和空列
’‘’
sheet.insert_rows(idx=数字编号,amount=要插入的行数)
sheet.insert_cols(idx=数字编号,amount=要插入的列数)
‘’‘
from openpyxl import load_workbook
filePath = r'D:\小学.xlsx'
workbook = load_workbook(filePath)
sheet = workbook["花名册"]
sheet.insert_rows(idx=3,amount=2)
sheet.insert_cols(idx=2,amount=1)
workbook.save(filePath)
2.5、删除行和列
’‘’
sheet.delete_rows(idx=数字编号,amount= 要删除的行数)
sheet.delete_cols(idx =数字编号,amount= 要删除的列数)
‘’‘
from openpyxl import load_workbook
filePath = r'D:\小学.xlsx'
workbook = load_workbook(filePath)
sheet = workbook["花名册"]
sheet.delete_rows(idx=3,amount=2)
sheet.delete_cols(idx=2,amount=1)
workbook.save(filePath)
2.6、创建新的sheet表create_sheet(“表名”))
from openpyxl import load_workbook
filePath = r'D:\小学.xlsx'
workbook = load_workbook(filePath)
workbook.create_sheet("身高")
sheet = workbook["身高"]
data = [
['学号', '身高'],
['1', '168'],
['2', '181'],
['3', '160'],
['4', '160'],
['5', '160'],
['6', '170'],
['7', '190']
]
for row in data:
sheet.append(row)
workbook.save(filePath)
2.7、删除sheet表(remove(表))
from openpyxl import load_workbook
filePath = r'D:\小学.xlsx'
workbook = load_workbook(filePath)
sheet=workbook["Sheet3"]
workbook.save(filePath)
2.8、新建Excel和修改sheet表名
from openpyxl import Workbook
workbook=Workbook()
sheet = workbook.active
sheet.title='表格'
workbook.save(filename=r'D:\新建Excel.xlsx')
2.9、合并多个Excel表格中的数据
import time
from openpyxL import Workbook, load_workbook
import os
def 合并表格(file_path, save_path):
files_name = os.listdir(file_path)
new_wb = Workbook()
new_ws = new_wb. active
header = ['销售日期', '员工工号','销售员', '货号','销售单号','销量','销售额']
new_ws.append(header)
for file_name in files_name :
wb = load_workbook(file_path + "\\"+ file_name )
for sheet in wb.sheetnames:
ws = wb[sheet]
for row in ws.iter_rows(min_row=2, values_only=True):
new_ws.append(row)
print('全年销售数据为%s行' % (new_ws.max_row - 1))
new_wb.save(save_path + "\\"+ "全年数据.xlsx")
开始时间=time.time()
合并表格(r"D:\2021年销售明细",r"D:\2021年销售明细")
print('合并完成耗时:',time.time() - 开始时间,"秒")
设置图标样式和单元格属性
from openpyxl.styles import Font, PatternFill, Alignment, Border, fills, colors,Side
from openpyxL import Workbook, load_workbook
from openpyxL.styles import Font, PatternFill,Alignment, Border, fills, colors, Side
filePath = r"D: \2021年销售明细\全年数据.xlsx"
wb = load_workbook(filePath)
ws = wb.active
ws.coLumn_dimensions["A"] .width = 25
ws.column_dimensions["B"] .width = 10
ws.coLumn_dimensions["C"] .width = 10
ws.coLumn_dimensions["D"] .width = 13
ws.coLumn_dimensions["E"] .width = 35
ws.column_dimensions["F"] .width = 8
ws.column_dimensions["G"].width = 10
font = Font("微软雅黑",size=12, color=colors.BLACK,bold=False)
fill = PatternFill(fill_type="solid", start_color="CDCDCD", end_color="CDCDCD")
alignment = Alignment(horizontal="center", vertical="center", indent=0)
bd = Border(left=Side(border_style="thin", color=colors.BLACK),
right=Side (border_style="thin", color=colors.BLACK) ,
top=Side(border_style="thin", color=colors.BLACK),
bottom=Side(border_style="thin", color=colors.BLACK) ,
outline=Side(border_style="thin", color=colors.BLACK),
vertical=Side(border_style="thin", color=colors.BLACK) ,
horizontal=Side(border_style= "thin", color=colors. BLACK)
)
for irow, row in enumerate(ws.rows, start=1) :
font = font
fill = fill
alignment = alignment
border = bd
for cell in row:
cell.font = font
cell.fill = fill
cell.alignment = alignment
cell.border = bd
ft = Font("宋体", size=12, color=colors.BLUE, bold=True)
ws["A1"].font = ft
ws["B1"].font = ft
ws["C1"].font = ft
ws["D1"].font = ft
ws["E1"].font = ft
ws["F1"].font = ft
ws["G1"].font = ft
savePath = r"D: \2021年销售明细\全年数据-格式调整.xlsx"
wb.save( savePath)