"""
================================================
Python模块:Python操作excel(.xlsx)封装类MyPyXlsToXlsx、MyPyBook和MyPySheet
Date:2022年02月07日
================================================
"""
# -*- coding: utf-8 -*-
import openpyxl
import pandas as pd
from openpyxl.utils import column_index_from_string
from openpyxl.worksheet.worksheet import Worksheet
from openpyxl.chart import Reference, BarChart, LineChart, PieChart
from openpyxl.styles import Font, Alignment, Border, Side
import os
import os.path
from win32com.client import Dispatch
import win32com.client as win32
import gc
class MyPyXlsToXlsx:
"""
类功能: Python使用openpyxl操作将xls文件转换为xlsx文件格式类
"""
def __init__(self, strOpenFilePath: str):
xlsFilePath = strOpenFilePath
# 文件存在就加载,不存在就创建工作簿。
if os.path.exists(xlsFilePath):
# 文件存在就加载,加载失败就报错。
try:
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(xlsFilePath)
# FileFormat = 51 is for .xlsx extension
# FileFormat = 56 is for .xls extension
wb.SaveAs(xlsFilePath + "x", FileFormat=51)
wb.Close()
excel.Application.Quit()
os.remove(xlsFilePath) # 删除老的xls文件
except IOError:
print("加载xls文件失败!请检查!")
else:
print("已成功将xls文件转换为xlsx文件!!!\n")
else:
print("加载的xls文件不存在!请检查!")
class MyPyBook:
"""
类功能: Python使用openpyxl操作excel(.xlsx)封装类MyPyBook
"""
def __init__(self, strOpenFilePath: str, read_only: bool = False, data_only: bool = True):
"""
:function: 初始化功能,加载excel文件
:param strOpenFilePath:要打开的excel(.xlsx)文件路径
:param read_only: True只读,False读写
:param data_only: True读单元格数据,False读单元格公式
"""
self.strFilePath = strOpenFilePath # 工作簿路径
self.workbook = None # 工作簿对象
# 文件存在就加载,不存在就创建工作簿。
if os.path.exists(self.strFilePath):
# 文件存在就加载,加载失败就报错。
try:
self.workbook = openpyxl.load_workbook(self.strFilePath, read_only=read_only, data_only=data_only)
except IOError:
print("加载excel文件失败!请检查!")
else:
print("已成功加载excel文件(.xlsx)文件!!!\n")
else:
print("加载excel文件不存在!自动创建文件!")
self.workbook = openpyxl.Workbook() # 创建工作簿
# self.saveWorkBookData(self.strFilePath) # 保存工作簿
def openWorkSheet(self, strSheetName: str) -> Worksheet: # 表示此函数的返回值,是一个这样的类型,函数注解
"""
:function: 打开工作表功能
:param strSheetName: 要打开的工作表名称
:return: 返回打开的工作表Worksheet对象
"""
worksheet = None
if strSheetName in self.workbook.sheetnames:
worksheet = self.workbook[strSheetName]
else:
print("表单名称在当前excel文件中不存在,请检查表单名称!")
return worksheet
def getFilePath(self):
"""
:function: 获取工作簿的绝对路径
:return: 返回工作簿的绝对路径
"""
return self.strFilePath # 工作簿路径
def getActiveSheet(self):
"""
:function: 获取当前活动工作表功能
:return: 返回活动的工作表对象
"""
return self.workbook.active
def saveWorkBookData(self):
"""
:function: 保存工作簿数据功能
"""
try:
self.workbook.save(self.strFilePath)
except PermissionError:
print("要操作的文件,没有写入权限,请检查权限!")
raise
except FileNotFoundError:
print("文件路径不存在,请确保路径正确!")
raise
except Exception:
print("保存写入的数据失败!请检查异常!")
raise
def closeWorkBook(self):
"""
:function: 关闭工作簿功能
"""
self.workbook.close()
del self.workbook # workbook为打开的工作簿
gc.collect() # 内存马上就释放
def insertSheet(self, strNewSheetName: str, index: int = None):
"""
:function: 插入新的工作表
:param index:0到num之间整数取值,num为工作表总个数
:param strNewSheetName:插入的工作表名称
:return:插入的工作表对象,否则为False
"""
if index is None:
return self.workbook.create_sheet(strNewSheetName) # insert a new sheet at the end (default)
else:
# 类型检测
if type(index) is not int:
print("cur_num 数据类型错误!请确认为整数类型!")
return False
# 数字是否出范围
if index in range(0, len(self.workbook.worksheets) + 1):
return self.workbook.create_sheet(strNewSheetName, index)
else:
print("工作表索引超出了目前最大索引!")
return False
def deleteSheet(self, strDeleteSheetName: str):
"""
:function: 删除工作表
:param strDeleteSheetName: 待删除的工作表名称
"""
if strDeleteSheetName in self.workbook.sheetnames:
self.workbook.remove(self.workbook[strDeleteSheetName])
else:
print("表单名称在当前excel文件中不存在,请检查表单名称!")
def copySheetToNewWorkbook(self, strCopySheetName: str, strSaveNewFilePath: str):
"""
:function: 复制工作簿的其中一个工作表到新的工作簿
:param strCopySheetName: 待复制的工作表名称
:param strSaveNewFilePath: 待保存的新工作簿名称(例:new.xlsx)
"""
listSheetNames = []
listSheetNames = self.workbook.sheetnames
self.saveWorkBookData(strSaveNewFilePath)
if strCopySheetName in listSheetNames:
listSheetNames.remove(strCopySheetName)
for SheetName in listSheetNames:
self.workbook.remove(self.workbook[SheetName])
self.saveWorkBookData(strSaveNewFilePath)
else:
print("表单名称在当前excel文件中不存在,请检查表单名称!")
def justOpen(self):
"""
模拟手工打开excel表
"""
try:
xlApp = Dispatch("Excel.Application")
xlApp.Visible = False
xlBook = xlApp.Workbooks.Open(self.strFilePath)
xlBook.Save()
xlBook.Close()
except IOError:
print("请手工打开 %s 后,随便修改一个空值并保存" % self.strFilePath)
else:
print("已成功加载excel文件(.xlsx)文件!!!\n")
@staticmethod
def filterData(strSourceFileName: str, strSaveAsFileName: str, strSourceLabel: str, strTargetLabel: str):
"""
:function: 筛选表中有strTargetLabel标签数据,并另存新的文件
:param strSourceFileName: 源文件名,例:“source.xlsx”
:param strSaveAsFileName: 另存目标文件名,例:“target.xlsx”
:p
- 1
- 2
前往页