11

我可以用这个打开一个受密码保护的 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

我不确定如何将信息传输到熊猫数据框。我需要一个一个地读取单元格,还是有一种方便的方法可以做到这一点?

4

6 回答 6

6

假设起始单元格为 (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 构造函数。

于 2017-01-25T16:31:32.010 回答
6

来自大卫哈曼的网站(所有学分归他所有) 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
于 2018-04-28T20:59:57.513 回答
2

假设您可以使用 win32com API 将加密文件保存回磁盘(我意识到这可能会破坏目的),您可以立即调用顶级 pandas 函数read_excel。不过,您需要先安装xlrd(对于 Excel 2003)、xlwt(也适用于 2003)和openpyxl(对于 Excel 2007)的某种组合。是用于读取 Excel 文件的文档。目前 pandas 不支持使用 win32com API 读取 Excel 文件。如果您愿意,欢迎您打开 GitHub 问题

于 2013-06-20T16:26:44.303 回答
2

根据@ikeoddy 提供的建议,这应该将各个部分放在一起:

如何使用python打开受密码保护的excel文件?

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

Workbooks.Open 方法 (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 的回答:

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关闭excel工作簿

xl_wb.Close(False)
于 2018-10-26T20:12:37.703 回答
2

简单的解决方案

import io
import pandas as pd
import msoffcrypto

passwd = 'xyz'

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='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)
于 2021-08-20T19:29:14.327 回答
1

添加到@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
于 2021-07-08T07:28:12.883 回答