英文:
How to detect if the xlsx file is password protected or not in python?
问题
我需要检测Excel文件是否受密码保护。如果受密码保护,请要求用户输入密码。我该如何在Python中实现这一功能?我在互联网上查找了一些信息,目前还没有找到有用的答案。
英文:
I have a required where I need to detect if the excel file is password protected or not. If password protected ask user for the password.
How do I do this in python?
I looked a bit on the internet, none of the answers were useful so far
答案1
得分: 1
以下是您要翻译的内容:
You could do something along these lines I guess.<br>
If the file is encrypted it will pass and the password can be requested.<br>
If it's not, it will error and the file can be loaded normally.<br>
import openpyxl
import io
import msoffcrypto
from msoffcrypto.exceptions import FileFormatError # pip install msoffcrypto-tool
filename = 'foo.xlsx'
with open(filename, 'rb') as file:
try:
workbook = io.BytesIO()
office_file = msoffcrypto.OfficeFile(file)
print("File is password protected")
passwd = input("Please enter file password")
office_file.load_key(password=passwd)
office_file.decrypt(workbook)
except FileFormatError as e:
print(e)
print("File is not password protected")
workbook=filename
wb = openpyxl.load_workbook(workbook)
ws = wb['Sheet1']
print(ws['A1'].value)
英文:
You could do something along these lines I guess.<br>
If the file is encrypted it will pass and the password can be requested.<br>
If it's not, it will error and the file can be loaded normally.<br>
import openpyxl
import io
import msoffcrypto
from msoffcrypto.exceptions import FileFormatError # pip install msoffcrypto-tool
filename = 'foo.xlsx'
with open(filename, 'rb') as file:
try:
workbook = io.BytesIO()
office_file = msoffcrypto.OfficeFile(file)
print("File is password protected")
passwd = input("Please enter file password")
office_file.load_key(password=passwd)
office_file.decrypt(workbook)
except FileFormatError as e:
print(e)
print("File is not password protected")
workbook=filename
wb = openpyxl.load_workbook(workbook)
ws = wb['Sheet1']
print(ws['A1'].value)
答案2
得分: 0
我找到了解决方案,在这个链接中 - https://github.com/nolze/msoffcrypto-tool/blob/03d3298f7b8e27a26280bab1702bad36cce2e398/msoffcrypto/__main__.py#L23
import msoffcrypto
file_c = msoffcrypto.OfficeFile(content)
is_pwd_protected = file_c.is_encrypted() # 如果文件受密码保护,is_encrypted将返回True。
英文:
after digging into the library I found the solution - https://github.com/nolze/msoffcrypto-tool/blob/03d3298f7b8e27a26280bab1702bad36cce2e398/msoffcrypto/__main__.py#L23
import msoffcrypto
file_c = msoffcrypto.OfficeFile(content)
is_pwd_protected = file_c.is_encrypted() #is_encrypted returns True if the file is password protected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论