openpyxl 给excel表增加下拉菜单
时间: 2023-07-08 17:31:34 浏览: 876
要在 Excel 表格中创建下拉菜单,可以使用 Python 的 `openpyxl` 模块。下面是一个简单的示例代码,演示如何使用 `openpyxl` 将下拉菜单添加到 Excel 表格中:
```python
from openpyxl import Workbook
from openpyxl.worksheet.datavalidation import DataValidation
# 创建一个新的 Excel 文件
workbook = Workbook()
# 创建一个新的工作表
worksheet = workbook.active
# 定义下拉菜单的选项列表
options = ['Apple', 'Banana', 'Cherry', 'Date']
# 创建一个数据验证对象
validation = DataValidation(type="list", formula1=f'"{",".join(options)}"', allow_blank=True)
# 将数据验证对象应用到单元格
worksheet.add_data_validation(validation)
validation.add('A1')
# 写入数据并保存 Excel 文件
worksheet['A1'] = 'Select Fruit'
worksheet['B1'] = 'Enter your fruit choice:'
workbook.save('example.xlsx')
```
在上面的示例代码中,我们首先创建一个新的 Excel 文件和工作表。然后,我们定义了下拉菜单的选项列表,并使用 `DataValidation()` 方法创建了一个数据验证对象。接下来,我们使用 `worksheet.add_data_validation()` 方法将数据验证对象添加到工作表,并使用 `validation.add()` 方法将其应用到单元格。最后,我们使用 `worksheet['A1']` 和 `worksheet['B1']` 分别写入了标题和数据。您可以根据需要更改单元格位置和选项列表。
阅读全文
相关推荐


















