[英]From password-protected Excel file to pandas 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
我不確定如何將信息傳遞給pandas數據幀。 我是否需要逐個讀取單元格,或者是否有方便的方法來實現?
假設起始單元格為(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單元格B5在win32com中作為第5行,第2列給出。 此外,我們需要list(...)從元組的元組轉換為元組列表,因為沒有用於元組元組的pandas.DataFrame構造函數。
假設您可以使用win32com API將加密文件保存回磁盤(我意識到可能會失敗),您可以立即調用頂級pandas函數read_excel
。 您需要首先安裝xlrd
(適用於Excel 2003), xlwt
(也適用於2003)和openpyxl
(適用於Excel 2007)的某些組合。 這是用於閱讀Excel文件的文檔。 目前,pandas不支持使用win32com API讀取Excel文件。 如果您願意,歡迎您打開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)
# You are prompted to provide the password to open the file
xl_app = win32com.client.Dispatch('Excel.Application')
pwd = getpass.getpass('Enter file password: ')
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的回答:
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()
xl_wb.Close(False)
來自David Hamann的網站(所有學分歸他所有) 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.