LoginSignup
Hiromi1623
@Hiromi1623

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

2つのExcelファイルの差分抽出プログラム

解決したいこと

2つのExcelファイルを比較して差分を新たなExcelファイルに抽出するプログラムを作成しました。
新たなExcelファイルには[シート名、セル番号、Excelデータの差分]をそれぞれ出力できるようにしたのですが、セル番号の欄が「Unnamed194」のように数字のまま出力されてしまいます。
原因としてはデータフレームとしてデータを扱う際に英数字から変更したデータがそのまま出力されていると考えているのですが、戻し方がわかりません。
どうしたら「A12」のような出力になるでしょうか?

発生している問題・エラー

Excelのセル番号が数字のまま出力されてしまう。

該当するソースコード

import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Alignment
from openpyxl.utils import get_column_letter

def compare_excel_files(file_path1, file_path2, sheet_names):
    # 出力データを格納するリスト
    output_data = []

    # Excelファイルを読み込む
    df1 = pd.read_excel(file_path1, sheet_name=None)
    df2 = pd.read_excel(file_path2, sheet_name=None)

    for sheet_name in sheet_names:
        # データの差分を抽出
        df1_sheet = df1[sheet_name]
        df2_sheet = df2[sheet_name]
        diff_data = df2_sheet[df2 != df1]
        diff_data.dropna(how='all', inplace=True)

        # 差分がある場合は出力データに追加
        if not diff_data.empty:
            # 差分データを整形して出力データに追加
            for row_index, row in diff_data.iterrows():
                for col_name, cell_value in row.items():
                    if pd.notnull(cell_value):
                        column_letter = get_column_letter(df.columns.get_loc(col_name) + 1)
                        output_data.append([sheet_name, f"{column_letter}{row_index+2}", df1.loc[row_index, col_name], df2.loc[row_index, col_name]])

    # 出力データをDataFrameに変換
    output_df = pd.DataFrame(output_data, columns=['シート名', 'セル', '差異1', '差異2'])

    # 出力データをExcelファイルに保存
    output_path = "output.xlsx"
    output_df.to_excel(output_path, index=False)

    # Excelファイルを開いてセル幅とテキスト配置を調整
    wb = load_workbook(output_path)
    for sheet_name in wb.sheetnames:
        ws = wb[sheet_name]
        for column_cells in ws.columns:
            max_length = 0
            for cell in column_cells:
                if cell.value is not None:
                    cell_length = len(str(cell.value))
                    if cell_length > max_length:
                        max_length = cell_length
            adjusted_width = (max_length + 2) * 1.0
            column_letter=column_cells[0].colmun_letter
            ws.column_dimensions[column_letter].width=adjusted_width

            # テキスト配置を左詰めに設定
            for cell in column_cells:
                cell.alignment = Alignment(horizontal='left')

    # 変更を保存
    wb.save(output_path)


# ファイルのパスと比較するシートのリストを指定してデータを比較
file_path1 = "【サンプル1】.xlsx"
file_path2 = "【サンプル2】.xlsx"
sheet_names = ['シート名']
compare_excel_files(file_path1, file_path2, sheet_names)

自分で試したこと

差分プログラムを作成した

0

2Answer

Your answer might help someone💌