网络编程
位置:首页>> 网络编程>> Python编程>> Python还能这么玩之只用30行代码从excel提取个人值班表

Python还能这么玩之只用30行代码从excel提取个人值班表

作者:Rattenking  发布时间:2022-05-03 22:49:45 

标签:Python,excel,提取,表

一、查找操作

1.Excel 模块 xlrd,xlwt,xlutils 分别负责 Excel 文件的读、写、读写转换工作!

2.openpyxl 直接可以对 Excel 文件读写!

3.pandas 直接可以对 Excel 文件读写!

二、安装 openpyxl 模块


pip install openpyxl

三、读取并筛选值班表中自己的信息

1.读取所有的值班信息;

2.由于一般情况 excel 都会有部分表格为空,保存全部 None 的 excel 行字符串数据;

3.循环全部的值班数据,将当前行数据形成一个数据字符串;

4.判断当前值班信息字符串是否含有自己的姓名;

5.对含有自己信息的数据中关键信息(值班时间,姓名)进行存储;

6.然后判断当前字符串是否含有全部 None 的数据;

7.由于值班表没有空出的行,所以查到 None,直接跳出循环。


dutys = []
 book = openpyxl.load_workbook('duty.xlsx',data_only=True)
 sheet = book.active
 all_data = book.get_sheet_by_name("日常加班")
 none_str = ''.join([str(None).ljust(20) for c in range(1,all_data.max_column+1)])
 for r in range(1,all_data.max_row + 1):
   cur_str = ''.join([str(all_data.cell(row=r,column=c).value).ljust(20) for c in range(1,all_data.max_column+1)])
   if cur_str.find("***") >= 0:
     dutys.append({
       "date": all_data.cell(row=r,column=2).value,
       "name": all_data.cell(row=r,column=3).value
     })
   elif cur_str.find(none_str) >= 0:
     break
 return dutys

四、创建自己的值班信息表

1.创建一个值班信息表的 excel;

2.将自己的值班信息循环;

3.将信息填入创建的表格。


book = openpyxl.Workbook()
 sheet = book.active
 for i in range(len(dutys)):
   sheet.cell(row=1 + i, column=1).value = dutys[i].get("name")
   sheet.cell(row=1 + i, column=2).value = f'{dutys[i].get("date")}'
 book.save('my_duty.xlsx')

五、全部代码


#!/usr/bin/env python
"""
@Author  :Rattenking
@Date    :2021/06/02 10:19
@CSDN :https://blog.csdn.net/m0_38082783
"""

import openpyxl
import time

def get_my_duty_date():
 dutys = []
 book = openpyxl.load_workbook('duty.xlsx',data_only=True)
 sheet = book.active
 all_data = book.get_sheet_by_name("日常加班")
 none_str = ''.join([str(None).ljust(20) for c in range(1,all_data.max_column+1)])
 for r in range(1,all_data.max_row + 1):
   cur_str = ''.join([str(all_data.cell(row=r,column=c).value).ljust(20) for c in range(1,all_data.max_column+1)])
   if cur_str.find("***") >= 0:
     dutys.append({
       "date": all_data.cell(row=r,column=2).value,
       "name": all_data.cell(row=r,column=3).value
     })
   elif cur_str.find(none_str) >= 0:
     break
 return dutys

def create_my_duty_list(dutys):
 book = openpyxl.Workbook()
 sheet = book.active
 for i in range(len(dutys)):
   sheet.cell(row=1 + i, column=1).value = dutys[i].get("name")
   sheet.cell(row=1 + i, column=2).value = f'{dutys[i].get("date")}'
 book.save('my_duty.xlsx')

if __name__ == "__main__":
 start_time = int(round(time.time() * 1000))
 dutys = get_my_duty_date()
 create_my_duty_list(dutys)
 end_time = int(round(time.time() * 1000))
 print(f'本次提取值班表时间:{end_time - start_time}ms')

六、执行结果

Python还能这么玩之只用30行代码从excel提取个人值班表

七、总结

熟悉 openpyxl 模块的各个功能,方便对 excel 的操作;筛选提取自己关注的关键信息,重新建表;下一篇根据值班时间,用 python 自动给自己的微信发送信息,进行提示!

来源:https://blog.csdn.net/m0_38082783/article/details/117463183

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com