Openpyxl库只能处理.xlsx的excel文件, 而xlrd无法获取页眉页脚信息, 使用win32com库调用excel软件来获取页眉, 需要电脑上安装office软件.
1. python 安装win32com
pip install pypiwin32
2. win32com 调用excel文件获取页眉信息,excel表格中页眉页脚分为左中右三部分
def choose_version(file):
excel = client.DispatchEx('Excel.Application')
wb = excel.Workbooks.Open(file)
# 屏蔽弹窗
wb.Checkcompatibility = False
# 1:打开宏,2:禁用宏
wb.RunAutoMacros(2)
for sheetObj in wb.Worksheets:
d = sheetObj.PageSetup.RightHeader #LeftHeader CenterHeader RightFooter
print(d)
wb.Close()
excel.Application.Quit()
3. 关闭打开的Excel进程的另一种方式(杀进程):
def close_excel_by_force(excel):
import win32process
import win32api
import win32con
# Get the window's process id's
hwnd = excel.Hwnd
t, p = win32process.GetWindowThreadProcessId(hwnd)
# Ask window nicely to close
try:
handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
if handle:
win32api.TerminateProcess(handle, 0)
win32api.CloseHandle(handle)
except:
pass
#logger.py
import time
import os
import logging
from logging import handlers
formater = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'
#路径管理
def log_path_check():
log_path = os.getcwd() + '/Logs/'
if not os.path.exists(log_path):
os.mkdir(log_path)
day = time.strftime('%Y-%m-%d', time.localtime())
log_name = log_path + day + '.log'
return log_name
class Logger(object):
def __init__(self, filename=log_path_check(), level='warning', when='D',backCount=3,
fmt=formater:
self.level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
} # 日志级别关系映射
self.logger = logging.getLogger()
format_str = logging.Formatter(fmt)#设置日志格式
self.logger.setLevel(self.level_relations.get(level))#设置日志级别
sh = logging.StreamHandler()#往屏幕上输出
sh.setFormatter(format_str) #设置屏幕上显示的格式
th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='GBK')#往文件里写入#指定间隔时间自动生成文件的处理器
#实例化TimedRotatingFileHandler
#interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
# S 秒
# M 分
# H 小时、
# D 天、
# W 每星期(interval==0时代表星期一)
# midnight 每天凌晨
th.setFormatter(format_str)#设置文件里写入的格式
self.logger.addHandler(sh) #把对象加到logger里
self.logger.addHandler(th)
log = Logger()
if __name__ == '__main__':
log = Logger('all.log',level='debug')
log.logger.debug('debug')
log.logger.info('info')
log.logger.warning('警告')
log.logger.error('报错')
log.logger.critical('严重')
Logger('error.log', level='error').logger.error('error')