求助,使用Python合并多个EXCEL表格时,如果表格有密码,密码已知,该怎么通过pandas合并,

如题所述

pandas是为Python编程语言编写的用于数据处理和分析的软件库。合并同一目录下的多个excel文件是办公中经常遇到的场景,本文将利用pandas完成该操作。
1 引入作案工具(pandas 和 路径工具)
import pandas as pd
from pathlib import Path
2 传入excel所在目录
excel_dir = Path('excel目录,如:E:/excel_files')
3 获取到路径下面的 excel 文件列表
excel_files = excel_dir.glob('*.xlsx')
4 创建 pandas 表格类型 dataFrame
df = pd.DataFrame()
5 遍历excel文件,读到数据添加到pandas表格中
for xls in excel_files:
data = pd.read_excel(xls, 'sheet_name')
df = df.append(data)
6 将pandas表格中所有数据(合并后的excel数据)写入到新的excel中
df.to_excel(excel_dir / "output.xlsx")追问

因为待合并的EXCEL表格有密码,所以在pd.read_excel(xls, 'sheet_name')读取的时候会提示失败,想问下这个情况怎么解决?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2021-08-20

    安装msoffcrypto-tool:pip install msoffcrypto-tool

    执行以下代码:

import msoffcrypto
import io
import pandas as pd

file = msoffcrypto.OfficeFile(open("encrypted.xlsx", "rb"))

file.load_key(password="Passw0rd") # Use password

decrypted = io.BytesIO()
file.decrypt(decrypted)

df = pd.read_excel(decrypted)
print(df)

3. 合并多个Excel表格:data = pd.concat([df0, df1, ...], axis=0)

追问

如果我想打开的是一个文件夹下面的多个文件,请问一下这个代码:file = msoffcrypto.OfficeFile(open("encrypted.xlsx", "rb"))该如何修改一下,还有在合并的时候会提示 name 'df1' is not defined