python实现Excel自动化办公

准备工作

  • 安装相关模块

pip install openpyxl lxml pillow

  • 基本定义

工作簿:一个电子表文件为一个工作簿

活动表:用户当前查看的表活关闭Excel最后查看的表

sheet表

单元格

Excel数据读取操作

  • 打开工作簿并创建一个对象:

wb = openpyxl.load_workbook('E:\PyCharm\pythonProject\test\venv\test.xlsx')

  • 获取工作簿中所有sheet表的表明:

wb.sheetnames

  • 获取指定的sheet表对象:

sheet = wb['升级内容']

  • 获取活动表对象:

sheet_ac = wb.active

  • 获取单元格对象:

cell = sheet['A4']

  • 获取单元格内容:

print(cell.value)

  • 获取坐标:

print(cell.row) #获取行坐标

print(cell.column) #获取列坐标

print(cell.coordinate) #获取整个坐标

  • 通过行、列索引定位单元格对象

print(sheet.cell(row=4,column=3).value)

  • 便利选定区域,选定区域返回为元组

for cell_row in sheet['C2':'D11']:

for cell in cell_row:

print(cell.value,cell.coordinate)

  • 获取特定行和列的单元格的值:利用工作表对象的rows和columns属性

返回一个生成器对象,可以用list()格式化成列表,并遍历指定的行或列)

print(list(sheet.rows))

print(list(sheet.columns))

for cell_row in list(sheet.rows)[0]:

print(cell_row.value)

for cell_row in list(sheet.columns)[0]:

print(cell_row.value)

  • 获取工作表中的最大行与最大列的数量

print(sheet.max_row,sheet.max_column)

写入Excel文档

  • 创建一个新的工作簿对象

wb = openpyxl.Workbook()

  • 给工作表改名

sheet.title = "记录表"

  • 保存工作簿

wb.save('C:\\Users\\Admin\\Desktop\\Date.xlsx')

  • 创建新工作表

wb.create_sheet(title='记录表2')

wb.create_sheet(index=1,title='记录表3')

#index=1:表示把新创建的工作表放在第几个位置

  • 删除工作表

del wb['记录表3']

  • 写入单元格

sheet['A1'] = 'hello'

sheet.cell(row=1, column=2).value = 100

单元格样式制定

  • 设置字体

导入字体工具类:

from openpyxl.styles import Font

设置字体:

sheet['A3'].font = Font(name = '楷体')

设置颜色:

sheet['A3'].font = Font(color = '8470FF')

其他设置:

italic = True #设置斜体

size = XXX #设置字体大小

underline='sigle' #设置单下划线

b = True #加粗

...

  • 设置背景填充色

导入背景填充色工具类

from openpyxl.styles import PatternFill

填充背景色

sheet['A3'].fill = PatternFill(patternType='solid',fgColor='8470FF')

#patternType='solid':patternType为填充样式,solid为填充整个单元格

  • 设置边框

导入边框工具类Side为边,Border为框

from openpyxl.styles import Side,Border

定制边框

#设置两个边对象,相当于两个模板

S1 = Side(style='thin',color='8470FF')

S2 = Side(style='double',color='ff0000')

#定义A3单元格上边框为S1模板样式

sheet['A3'].border = Border(top=S1)

#分别定义单元格A4的4个边框样式

sheet['A4'].border = Border(top=S2,bottom=S1,left=S2,right=S1)

  • 单元格对齐方式

导入对齐方式工具类

from openpyxl.styles import Alignment

定义对齐方式

#horizontal为水平对齐方式,left为左对齐

sheet['B2'].alignment = Alignment(horizontal='left')

数据筛选与排序

  • 定义筛选器

#auto_filter:定义一个筛选器对象,ref为选取范围

sheet.auto_filter.ref = 'C1:C280'

  • 给筛选器添加筛选条件

(会有一个bug,执行完其实已经生效但是excel表没有显示出来。需要点一下筛选确认一下才行)

#2为筛选第三列内容,['大肠菌群']为筛选条件

sheet.auto_filter.add_filter_column(2,['大肠菌群'])

  • 数据排序

#也需要先定义一个筛选器

sheet.auto_filter.ref = 'C1:C280'

#参数1:排序列, 参数2:升降序

sheet.auto_filter.add_sort_condition(ref='C3:C20',descending=True)

其他设置

  • 公式操作

添加公式

sheet['A3'] = '=SUM(A1:A2)'

在打开一个带有公式的表想要读取数据而不是公式时需要只读模式,有个bug:如果没有生效需要打开excel重新保存一遍

xl = openpyxl.load_workbook('C:\\Users\\Administrator\\Desktop\\10.19.xlsx',read_only=True)

  • 设置行列

设置行高

#sheet.row_dimensions:获取行,返回为包含行对象的字典,一行一个key和对应的对象值。选择key为2对应的对象也就是第二行高度设置成50

sheet.row_dimensions[2].height = 50

设置列宽

sheet.column_dimensions['A'].width = 80

  • 拆分合并单元格

合并单元格

sheet.merge_cells('A1:D7')

拆分单元格

sheet.unmerge_cells('A1:D7')

  • 冻结与解冻窗口

冻结

sheet.freeze_panes = 'A2'

解冻

sheet.freeze_panes = None

绘制图表

#'G1':为图标添加的位置

综合示例

如下表,公司要求每天统计两个sheet页企业和政府中检测项目的检测次数和检测方法简称并输出到新的excel中,其中检测项目后缀带数字的为检测次数(例如有两个大肠杆菌*5,两个大肠杆菌,总次数为2*5+2)

代码:

python 复制代码
from  openpyxl.styles import  Alignment
import  openpyxl
xl = openpyxl.load_workbook('C:\\Users\\Admin\\Desktop\\10.19.xlsx')
ls = xl.sheetnames
sheet1 = xl[ls[0]]
sheet2 = xl[ls[1]]
countDate = {}

for row in range(2,sheet1.max_row + 1):
    state = sheet1['C' + str(row)].value
    name = sheet1['D' + str(row)].value
    if state != None:
        countDate.setdefault(state,{'counts':0,'检测方法简称':name})
        countDate[state]['counts'] += 1
        print(countDate)
for row in range(2,sheet2.max_row + 1):
    state = sheet2['C' + str(row)].value
    name = sheet2['D' + str(row)].value
    if state != None:
        countDate.setdefault(state,{'counts':0,'检测方法简称':name})
        countDate[state]['counts'] += 1

countNum = {}
for key,value in countDate.items():
    numm = key.find('*')
    if numm < 0:
        if countNum.get(key) == None:
            countNum.setdefault(key,value)
        else:
            countNum[key]['counts'] += int(countDate[key]['counts'])

    else:
        names = key[0:numm]
        nums =int(key[numm+1:]) * int(countDate[key]['counts'])
        namess = countDate[key]['检测方法简称']
        if countNum.get(names) == None:
            countNum.setdefault(names,{'counts':nums,'检测方法简称':namess})
        else:
            countNum[names]['counts'] += nums
print("++++++++++++++++++++++++++++++++++")
print(countNum)

wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = '统计数据'
sheet.column_dimensions['A'].width=25
sheet.column_dimensions['A'].horizontal='left'
sheet.column_dimensions['C'].width=100
no1 = 0

for key,value in countNum.items():
    no1 += 1
    sheet.cell(row = no1 , column=1).value = key
    sheet.cell(row=no1, column=2).value = countNum[key]['counts']
    sheet.cell(row=no1, column=2).alignment = Alignment(horizontal='left')
    sheet.cell(row=no1, column=3).value = countNum[key]['检测方法简称']

wb.save('C:\\Users\\Admin\\Desktop\\Date.xlsx')
相关推荐
巴里巴气18 分钟前
Python爬虫图片验证码和滑块验证码识别总结
爬虫·python
sword devil9001 小时前
PYQT实战:智能家居中控
python·智能家居·pyqt
NetX行者1 小时前
FastMCP:用于构建MCP服务器的开源Python框架
服务器·python·开源
超龄超能程序猿1 小时前
(3)机器学习小白入门 YOLOv: 解锁图片分类新技能
python·numpy·pandas·scipy
waynaqua1 小时前
FastAPI开发AI应用一:实现连续多轮对话
python·openai
纨妙1 小时前
python打卡day59
开发语言·python
waynaqua1 小时前
FastAPI开发AI应用二:多厂商模型使用指南
python·openai
秋难降1 小时前
Python 知识 “八股”:给有 C 和 Java 基础的你😁😁😁
java·python·c
FF-Studio2 小时前
大语言模型(LLM)课程学习(Curriculum Learning)、数据课程(data curriculum)指南:从原理到实践
人工智能·python·深度学习·神经网络·机器学习·语言模型·自然语言处理
PHOSKEY2 小时前
闪测仪应用案例丨手机中框如何突破「尺寸检测」瓶颈?
运维·智能手机·自动化