From password-protected Excel file to pandas DataFrame

前端 未结 4 899
青春惊慌失措
青春惊慌失措 2020-12-15 11:42

I can open a password-protected Excel file with this:

import sys
import win32com.client
xlApp = win32com.client.Dispatch(\"Excel.Application\")
print \"Excel         


        
4条回答
  •  青春惊慌失措
    2020-12-15 12:05

    Based on the suggestion provided by @ikeoddy, this should put the pieces together:

    How to open a password protected excel file using python?

    # 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)
    

    Getting command-line password input in 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: ')
    

    Workbooks.Open Method (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)
    

    ikeoddy's answer:

    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 closing excel workbook

    xl_wb.Close(False)
    

提交回复
热议问题