excel对比脚本
对比excel
from os.path import exists
from xlwings import App
def check_list_tool():
if not exists('主管.xlsx'):
print("缺少主管文件,无法比较")
return
# 打开主管.xlsx,并读取所有工作表名称
app = App(visible=False, add_book=False)
try:
super_book = app.books.open('主管.xlsx')
sheets = [sheet.name for sheet in super_book.sheets]
finally:
super_book.close()
app.quit()
# 对每个工作表,检查是否有同名的 Excel 文件
for sheet_name in sheets:
if sheet_name == "方案主要尺寸":
continue
file_name = f"{sheet_name[:-4]}.xlsx"
if exists(file_name):
comparison_successful = do_compare('主管.xlsx', file_name, sheet_name, sheet_name, "B1:B50")
if comparison_successful:
print(f"{sheet_name}比较已完成")
else:
print(f"警告: 主管文件中存在工作表 '{sheet_name}',但找不到对应的 Excel 文件 '{file_name}'")
def do_compare(super_book_name, design_book_name, super_sheet_name, design_sheet_name, range_to_compare):
app = App(visible=False, add_book=False) # Set visible=False to run in the background
try:
super_book = app.books.open(super_book_name)
design_book = app.books.open(design_book_name)
# 检查被比较的文件中是否有相应的工作表
if design_sheet_name not in [sheet.name for sheet in design_book.sheets]:
print(f"警告: 被比较文件 '{design_book_name}' 中不存在工作表 '{design_sheet_name}'")
return False
for row in super_book.sheets[super_sheet_name].range(range_to_compare):
for super_cell in row:
design_cell = design_book.sheets[design_sheet_name].range(super_cell.address)
if super_cell.value != design_cell.value:
super_cell.color = design_cell.color = (255, 180, 180) # 红色,表示不一致
else:
super_cell.color = design_cell.color = (200, 255, 200) # 绿色,表示一致
super_book.save()
design_book.save()
return True
except Exception as e:
print(f"比较过程中出现错误: {e},请企业微信联系赵子雯")
return False
finally:
if 'super_book' in locals():
super_book.close()
if 'design_book' in locals():
design_book.close()
app.quit()
if __name__ == '__main__':
print("1.请先确认excel已彻底关闭")
print("2.请确保文件夹中包含 主管.xlsx, 以及其他需要比较的文件")
print("3.比较后一致的是绿色,不一致的是红色,没有比较的不改变")
print("继续请按回车")
input()
check_list_tool()
print("程序已结束 ^_^,按任意键退出")
input()
打包成exe,使用conda环境精简一点,pip安装pyinstaller。然后pyinstaller -F main.py
一般没问题,有可能会超
运行这个,在pycharm的terminal中运行一次,会超过迭代次数。此时加入下面的代码。可以搜到教程。
import sys ; sys.setrecursionlimit(sys.getrecursionlimit() * 5)
浙公网安备 33010602011771号