使用pandas从excel读取下拉值

2024-04-23 12:01:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带下拉单元格的excel。我一直试图阅读excel下拉列表,但它只读取选定的选项。在

enter image description here

import pandas

df = pandas.read_excel("BQA.xlsx", header=0)
df.columns = df.columns.str.strip()

print(df)

输出:

^{pr2}$

预期产量:

Empty DataFrame
Columns: [Column 1, Column 2, Column 3, Column 4, [yes, no, yes1, no1]]
Index: []

Tags: columnsimportpandasdf列表read选项column
1条回答
网友
1楼 · 发布于 2024-04-23 12:01:39

您可以使用openpyxl来提取下拉列表信息:它存储在给定工作表的数据验证中。例如(为了可读性插入新行):

>>> wb = openpyxl.load_workbook("dropdown.xlsx")
>>> ws = wb["Sheet1"]
>>> ws.data_validations
<openpyxl.worksheet.datavalidation.DataValidationList object>
Parameters:
disablePrompts=None, xWindow=None, yWindow=None, count=1, 
dataValidation=[<openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
sqref=<MultiCellRange [E1]>, showErrorMessage=True, showDropDown=None, showInputMessage=True, 
allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None,
type='list', errorStyle=None, imeMode=None, operator=None, formula1='$L$4:$L$7', formula2=None]

我不打算处理所有可能的情况,所以这只是你可以做的事情的一个例子,但是

^{pr2}$

给我(再次插入新行):

>>> data = read_with_dropdown("dropdown.xlsx", "Sheet1", "A1:E5")
>>> data
[['Column 1', 'Column 2', 'Column 3', 'Column 4', ['yes', 'no', 'yes1', 'no1']],
 [None, None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None]]

相关问题 更多 >