以下脚本适用于.xlsm和.xlsb文件,直到我尝试计算Excel密码保护文件。这是我正在尝试改进和分析的现有流程 - 我将收到的工作表都受密码保护,作为文件名的前5个字符,并且都是.xlsb或.xlsm。
#Take xlsb Binary files, convert to csv, concatenate, keep file name
import pandas as pd
import os, glob, win32com.client
path = r'C:\Users\user\Desktop\Test Binary'
all_files_test = glob.glob(os.path.join(path, "*.xlsb"))
for file in all_files_test:
name1 = os.path.splitext(os.path.split(file)[1])[0]
name2 = name1[0:5]
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
doc = excel.Workbooks.Open(file,False, False, None, name2)
doc.Sheets(3).Select #3 for xlsm files - verify
csv_name = os.path.basename(file).replace('xlsb','csv') #xlsb xlsm
doc.SaveAs(Filename=os.path.join(path, 'CSV Out', csv_name),FileFormat = 6)
doc.Close(True)
excel.Quit()
excel.Quit()
files = glob.glob('c:/Users/user/Desktop/Test Binary/CSV Out/*.csv')
dfs = [pd.read_csv(fp).assign(orig_file_name=os.path.basename(fp)) for fp in files]
df = pd.concat(dfs, ignore_index=True)
df.head(10)
df.to_csv('c:/Users/user/Desktop/Test Binary/CSV Out/concat.csv',sep=',')
print("Done, check concatenated file.")
脚本通过第一个文件工作,但当它到达第二个文件时,它会出错:
Traceback (most recent call last):
File "C:\Users\user\Desktop\xlsb_csv_concat.py", line 28, in <module>
doc.Sheets(3).Select #3 for xlsm files - verify
AttributeError: 'NoneType' object has no attribute 'Sheets'
我确信有更有效的方法来完成我所写的内容,但它对于此特定任务运行良好,直到密码显示出来。在此先感谢您的帮助。
答案 0 :(得分:0)
万一有人遇到类似情况:
更改:
doc = excel.Workbooks.Open(file, False, False, None, name2)
到
doc = excel.Workbooks.Open(file, False, True, None, name2)
为我工作。