Excel文件对比改写前后内容差异--基于pandas数据处理及style应用

在我的工作有一项工作是征订报纸,在与同事和邮局沟通后核对提单的时候,因为数据量大,用眼睛来比较两份文件有点费眼,所以写了一段代码供以后用。

# -*- coding: utf-8 -*-
"""
@author Guo.decheng
@file: excel比较.py
@date: 2022/11/12
"""
import re

import pandas
from pandas import Series
from pandas import DataFrame
from typing import List


class excel_compare(object):
    """
    以PANDAS方式分析Excel,1是学习Pandas 2是分析数据比较方便,代码比以openpyxl简洁。

    """

    def __init__(self, file1: str, file2: str) -> None:
        self.dr = re.compile(r".+(?=\.xlsx|\.xls)").match(file1).group()
        self.data1: DataFrame = pandas.read_excel(file1)  # 从Excel中读取两个文件,做比较.
        self.data2: DataFrame = pandas.read_excel(file2)
        self.data2.replace(r'\s+','',regex=True,inplace=True)
        self.data1.replace(r'\s+','',regex=True,inplace=True)
        self.uncom_value: dict = {}  # 用以存储差异性数据
        self.commcol = set(self.data1.columns) & set(self.data2.columns)  # 存储共有的列名

        for col in self.commcol:
            self.uncom_value[col] = list(set(self.data1[col]) ^ set(self.data2[col]))

    def highlight_col(self, x: Series) -> List:  # 改变有差异内容的单元
        # print(x.name)      # pandas是一列一列的读取
        if x.name in self.commcol:
            mask = x.isin(self.uncom_value[x.name])
            return ['color:red;background-color: yellow' if v else '' for v in mask]
        else:
            return ['color:#008000'] * len(x)

    def highlight_row(self,x:Series)->List:
        if x.name%2:
            return ['background-color: #F5F5DC']*len(x)
        else:
            return ['background-color:#F0F8FF'] * len(x)
    def to_save(self) -> None:    # 将差异存储到Excel中
        file1_name=self.dr + "_a.xlsx"
        file2_name = self.dr + "_b.xlsx"
        self.data2.style.apply(self.highlight_col).to_excel(file2_name, index=False)
        # self.data1.style.apply(self.highlight_col).to_excel(file1_name, index=False)
        self.data1.style.apply(self.highlight_col).apply(self.highlight_col).apply(self.highlight_row,axis=1).to_excel(file1_name, index=False)



if __name__ == '__main__':
    file1_name = r'D:\工作\test1.xlsx'
    file2_name = r'D:\工作\test2.xlsx'

    test = excel_compare(file1_name, file2_name)
    test.to_save()

参考文章:1.Pandas 表格样式设置指南,看这一篇就够了! - 腾讯云开发者社区-腾讯云

                  2.Python 数据处理(四十)—— 输出样式 style - 知乎

                  3.python - function not being called when I call style.apply - Stack Overflow

                  4.Pandas replace无法去掉字符中空格问题_yikudeanu的博客-CSDN博客

你可能感兴趣的:(excel,pandas,python)