code

암호로 보호된 Excel 파일에서 Panda DataFrame까지

starcafe 2023. 6. 7. 23:03
반응형

암호로 보호된 Excel 파일에서 Panda DataFrame까지

다음을 사용하여 암호로 보호된 Excel 파일을 열 수 있습니다.

import sys
import win32com.client
xlApp = win32com.client.Dispatch("Excel.Application")
print "Excel library version:", xlApp.Version
filename, password = sys.argv[1:3]
xlwb = xlApp.Workbooks.Open(filename, Password=password)
# xlwb = xlApp.Workbooks.Open(filename)
xlws = xlwb.Sheets(1) # counts from 1, not from 0
print xlws.Name
print xlws.Cells(1, 1) # that's A1

판다 데이터 프레임으로 정보를 전송하는 방법은 잘 모르겠습니다.세포를 하나씩 다 읽어야 하나요, 아니면 이런 일이 일어나는데 편리한 방법이 있나요?

간단한 해결책

import io
import pandas as pd
import msoffcrypto

passwd = 'xyz'

decrypted_workbook = io.BytesIO()
with open(path_to_your_file, 'rb') as file:
    office_file = msoffcrypto.OfficeFile(file)
    office_file.load_key(password=passwd)
    office_file.decrypt(decrypted_workbook)

df = pd.read_excel(decrypted_workbook, sheet_name='abc')

pip install --user msoffcrypto-tool

디렉토리 및 하위 디렉토리에서 각 Excel의 모든 시트를 별도의 csv 파일로 내보내기

from glob import glob
PATH = "Active Cons data"

# Scaning all the excel files from directories and sub-directories
excel_files = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.xlsx'))] 

for i in excel_files:
    print(str(i))
    decrypted_workbook = io.BytesIO()
    with open(i, 'rb') as file:
        office_file = msoffcrypto.OfficeFile(file)
        office_file.load_key(password=passwd)
        office_file.decrypt(decrypted_workbook)

    df = pd.read_excel(decrypted_workbook, sheet_name=None)
    sheets_count = len(df.keys())
    sheet_l = list(df.keys())  # list of sheet names
    print(sheet_l)
    for i in range(sheets_count):
        sheet = sheet_l[i]
        df = pd.read_excel(decrypted_workbook, sheet_name=sheet)
        new_file = f"D:\\all_csv\\{sheet}.csv"
        df.to_csv(new_file, index=False)

시작 셀이 (StartRow, StartCol)로 지정되고 종료 셀이 (EndRow, EndCol)로 지정된다고 가정하면 다음과 같은 작업이 가능합니다.

# Get the content in the rectangular selection region
# content is a tuple of tuples
content = xlws.Range(xlws.Cells(StartRow, StartCol), xlws.Cells(EndRow, EndCol)).Value 

# Transfer content to pandas dataframe
dataframe = pandas.DataFrame(list(content))

참고: Excel Cell B5는 win32com의 5행, 2행으로 제공됩니다.또한 판다가 없기 때문에 튜플 목록에서 튜플 목록으로 변환하려면 목록(...)이 필요합니다.튜플의 데이터 프레임 생성자입니다.

데이비드 하만의 사이트에서 (모든 크레딧은 그에게 돌아간다) https://davidhamann.de/2018/02/21/read-password-protected-excel-files-into-pandas-dataframe/ .

xlwings를 사용하여 파일을 열면 먼저 Excel 응용 프로그램이 실행되어 암호를 입력할 수 있습니다.

import pandas as pd
import xlwings as xw

PATH = '/Users/me/Desktop/xlwings_sample.xlsx'
wb = xw.Book(PATH)
sheet = wb.sheets['sample']

df = sheet['A1:C4'].options(pd.DataFrame, index=False, header=True).value
df

win32com API를 사용하여 암호화된 파일을 다시 디스크에 저장할 수 있다고 가정하면(이는 목적을 달성하지 못할 수도 있음을 알고 있음) 즉시 최상위 판다 기능을 호출할 수 있습니다.read_excel몇 가지 조합을 설치해야 합니다.xlrd(Excel 2003의 경우)xlwt(2003년의 경우도 해당),openpyxl(Excel 2007의 경우) 먼저.여기 엑셀 파일로 읽을 수 있는 문서가 있습니다.현재 판다는 Win32com API를 사용하여 엑셀 파일을 읽는 것을 지원하지 않습니다.원한다면 GitHub 이슈를 열어보는 것을 환영합니다.

@ikeoddy가 제공한 제안에 따라 다음과 같이 부품을 조립해야 합니다.

파이썬을 사용하여 암호로 보호된 엑셀 파일을 여는 방법은 무엇입니까?

# Import modules
import pandas as pd
import win32com.client
import os
import getpass

# Name file variables
file_path = r'your_file_path'
file_name = r'your_file_name.extension'

full_name = os.path.join(file_path, file_name)
# print(full_name)

Python에서 명령줄 암호 입력을 가져오는 중

# You are prompted to provide the password to open the file
xl_app = win32com.client.Dispatch('Excel.Application')
pwd = getpass.getpass('Enter file password: ')

문제집.방법 열기(Excel)

xl_wb = xl_app.Workbooks.Open(full_name, False, True, None, pwd)
xl_app.Visible = False
xl_sh = xl_wb.Worksheets('your_sheet_name')

# Get last_row
row_num = 0
cell_val = ''
while cell_val != None:
    row_num += 1
    cell_val = xl_sh.Cells(row_num, 1).Value
    # print(row_num, '|', cell_val, type(cell_val))
last_row = row_num - 1
# print(last_row)

# Get last_column
col_num = 0
cell_val = ''
while cell_val != None:
    col_num += 1
    cell_val = xl_sh.Cells(1, col_num).Value
    # print(col_num, '|', cell_val, type(cell_val))
last_col = col_num - 1
# print(last_col)

아이코디의 대답:

content = xl_sh.Range(xl_sh.Cells(1, 1), xl_sh.Cells(last_row, last_col)).Value
# list(content)
df = pd.DataFrame(list(content[1:]), columns=content[0])
df.head()

python win32 COM 마감 엑셀 워크북

xl_wb.Close(False)

@Maurice 답변에 추가하여 범위를 지정할 필요 없이 시트의 모든 셀 가져오기

wb = xw.Book(PATH, password='somestring')
sheet = wb.sheets[0] #get first sheet

#sheet.used_range.address returns string of used range
df = sheet[sheet.used_range.address].options(pd.DataFrame, index=False, header=True).value

언급URL : https://stackoverflow.com/questions/15285068/from-password-protected-excel-file-to-pandas-dataframe

반응형