简体   繁体   English

python xlwings 不会在每次迭代中保存 excel 文件

[英]python xlwings won' t save the excel file in each iteration

This is a bit complex to explain, please ask if there are any doubts.这个解释起来有点复杂,如有疑问请追问。

I have two excel files named, initial and updated.我有两个命名为初始和更新的 excel 文件。 updated always has more sheets and maybe more rows in each sheet or changed values.更新总是有更多的工作表,每张工作表中可能有更多的行或更改的值。 I am trying to compare each sheet that exists in both initial and updated files and write and highlight the changes into a new excel file.我正在尝试比较初始文件和更新文件中存在的每个工作表,并将更改写入并突出显示到新的 excel 文件中。

This is the code that i have.这是我拥有的代码。

from pathlib import Path
import pandas as pd
import numpy as np
import xlwings as xw


initial_version = Path.cwd() / "ConfigurationReport_TEST.xlsx"
updated_version = Path.cwd() / "ConfigurationReport_DEV2.xlsx"

excel1 = pd.ExcelFile(initial_version)
excel2 = pd.ExcelFile(updated_version)

lesser_sheetnames_dict = {}
greater_sheetnames_dict  = {}

for idx, value in enumerate(excel1.sheet_names if len(excel1.sheet_names) < len(excel2.sheet_names) else excel2.sheet_names):
    lesser_sheetnames_dict[idx] = value
for idx, value in enumerate(excel1.sheet_names if len(excel1.sheet_names) > len(excel2.sheet_names) else excel2.sheet_names):
    greater_sheetnames_dict[idx] = value

print(lesser_sheetnames_dict)
print(len(lesser_sheetnames_dict))
print(len(greater_sheetnames_dict))

for sheetnum,sheetname in lesser_sheetnames_dict.items():
    if sheetname not in greater_sheetnames_dict.values():
        continue
    else:
        df1 = pd.read_excel(initial_version,sheet_name=sheetname)
        df2 = pd.read_excel(updated_version,sheet_name=sheetname)
        df1 = df1.fillna('')
        df2 = df2.fillna('')
        
        df2 = df2.reset_index()
        df3 = pd.merge(df1,df2,how='outer',indicator='Exist')
        df3 = df3.query("Exist != 'both'")
        df_highlight_right = df3.query("Exist == 'right_only'")

        df_highlight_left = df3.query("Exist == 'left_only'")

        highlight_rows_right = df_highlight_right['index'].tolist()
        highlight_rows_right = [int(row) for row in highlight_rows_right]

        first_row_in_excel = 2

        highlight_rows_right = [x + first_row_in_excel for x in highlight_rows_right]

        with xw.App(visible=False) as app:

            updated_wb = app.books.open(updated_version)
            print(updated_wb.sheets([x+1 for x in greater_sheetnames_dict.keys() if greater_sheetnames_dict[x] == sheetname][0]))
            updated_ws = updated_wb.sheets([x+1 for x in greater_sheetnames_dict.keys() if greater_sheetnames_dict[x] == sheetname][0])
            rng = updated_ws.used_range

            print(f"Used Range: {rng.address}")

            # Hightlight the rows in Excel
            for row in rng.rows:
                if row.row in highlight_rows_right:
                    row.color = (255, 71, 76)  # light red
                
            updated_wb.save(Path.cwd() / "Difference_Highlighted.xlsx")

The problem that im facing is in the with block.我面临的问题是在with块中。 Ideally this code should run for each sheet that exists in both the files and highlight the changes and save it into a new file.理想情况下,此代码应针对两个文件中存在的每个工作表运行,并突出显示更改并将其保存到新文件中。

But in this case, it runs for each sheet that exists in both the files, but only highlights and saves the last sheet.但在这种情况下,它会为两个文件中存在的每个工作表运行,但只突出显示并保存最后一个工作表。

Being my first interaction with xlwings library, i have very little idea on how that block works.作为我与 xlwings 库的第一次交互,我对该块的工作原理知之甚少。 Any assistance will be much appreciated.任何帮助将不胜感激。

I feel stupid to post this question now.我觉得现在发布这个问题很愚蠢。 The error was because of the the scope of with block.错误是因为 scope 的with块。 Since it was inside the if block, it kept opening a workbook every single time, wrote to it, highlighted the changes of the current sheet that's being iterated on, then saved it.由于它在if块内,它每次都打开一个工作簿,写入它,突出显示正在迭代的当前工作表的更改,然后保存它。 Obviously, during the last iteration(sheet) it opened the file again, wrote to it, highlighted the changes and overwritten the previously saved file.显然,在最后一次迭代(工作表)期间,它再次打开文件,写入文件,突出显示更改并覆盖先前保存的文件。

To avoid this, I moved the with block's opening statement to before if block, and now it works perfectly as intended.为了避免这种情况,我将 with 块的开头语句移到if块之前,现在它可以按预期完美运行。

with xw.App(visible=False) as app:
    for sheetnum,sheetname in lesser_sheetnames_dict.items():
        if sheetname not in greater_sheetnames_dict.values():
            continue
        else:
          // code                    
    updated_wb.save(Path.cwd() / "Difference_Highlighted.xlsx")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM