问:使用Python,如何测试两个不同名称的Excel文件是否具有相同的内容?
我试过的:我见过的大多数答案都建议使用filecmp.cmp或hash。我尝试过使用两者,但没有成功。特别是,假设'f1.xlsx'只有两个非空单元格:A1 ='hello'和B1 ='world'。接下来,将此内容复制并粘贴到新文件“f2.xlsx”。现在,两个文件在相同的单元格位置中恰好有两个非空条目。我得到以下结果:
>> f1 = 'f1.xlsx'
>> f2 = 'f2.xlsx'
#Using read():
>>> open(f1).read()==open(f2).read()
False
#Using filecmp.cmp:
>>> filecmp.cmp(f1, f2, shallow=True)
False
#Using izip:
>>> all(line1 == line2 for line1, line2 in izip_longest(f1, f2))
False
#Using hash:
>>> hash1=hashlib.md5()
>>> hash1.update(f1)
>>> hash1 = hash1.hexdigest()
>>> hash2=hashlib.md5()
>>> hash2.update(f2)
>>> hash2 = hash2.hexdigest()
>>> hash1==hash2
False
#also note, using getsize:
>>> os.path.getsize(f1)
8007
>>> os.path.getsize(f2)
8031
当然我可以使用Pandas将Excel文件解释为数据帧,然后使用标准比较(例如all())返回True,但我希望有更好的方法,例如这也适用于.docx文件。
提前致谢!我怀疑结在'标准'测试中使用像.xlsx或.docx这样的扩展,但希望有一种有效的方法来比较内容。
注意:如果它简化了问题,顺序无关紧要,如果f2有A1 ='world'而B1 ='hello',我想要返回“True”。
我在过去遇到了同样的问题,最后刚刚进行了一些“逐行”的比较。对于excel文件,我使用openpyxl模块,它具有一个很好的接口,可以逐个单元地挖掘文件。对于docx,我使用了python_docx模块。以下代码适用于我:
>>> from openpyxl import load_workbook
>>> from docx import Document
>>> f1 = Document('testDoc.docx')
>>> f2 = Document('testDoc.docx')
>>> wb1 = load_workbook('testBook.xlsx')
>>> wb2 = load_workbook('testBook.xlsx')
>>> s1 = wb1.get_active_sheet()
>>> s2 = wb2.get_active_sheet()
>>> def comp_xl(s1, s2):
>>> for row1, row2 in zip(s1.rows, s2.rows):
>>> for cell_1, cell_2 in zip(row1, row2):
>>> if isinstance(cell_1, openpyxl.cell.cell.MergedCell):
>>> continue
>>> elif not cell_1.value == cell_2.value:
>>> return False
>>> return True
>>> comp_xl(s1, s2)
True
>>> all(cell_1.value==cell_2.value for cell_1, cell_2 in zip((row for row in s1.rows), (row for row in s2.rows)) if isinstance(cell_1, openpyxl.cell.cell.Cell))
True
>>> def comp_docx(f1, f2):
>>> p1 = f1.paragraphs
>>> p2 = f2.paragraphs
>>> for i in range(len(p1)):
>>> if p1[i].text == p2[i].text:
>>> continue
>>> else: return False
>>> return True
>>> comp_docx(f1, f2)
True
>>> all(line1.text == line2.text for line1, line2 in zip(f1.paragraphs, f2.paragraphs))
True
它非常基本,显然没有考虑样式或格式,而只是测试它工作的两个文件的文本内容。希望这有助于某人。