gpt4 book ai didi

python - OpenPyXL:是否可以在 Excel 工作表中创建下拉菜单?

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:14 24 4
gpt4 key购买 nike

我正在尝试使用 openpyxl 在单元格中存储有效 IP 地址列表。目前数据只是简单地放在一个单元格中,通常会溢出到其他单元格中。使用以下代码:

# Regex to return a tidy list of ip addresses in that block
"""
r = row to be checked
s = source or destination columns
iptc = ips to check
"""

def regex_ips(r, s):
iptc = ['165.11.14.20', '166.22.24.0/24', '174.68.19.11', '165.211.20.0/23']
if r is not None:
if s is not None:
iptc = str(sheet.cell(r, s).value)
san = re.sub('\n', ', ', iptc)
sheet_report.cell(r, 8).value = san

但是,如果我可以将这些 IP 地址放入下拉列表中,我会更愿意,因为这样会更容易阅读 - 所以我的问题是双重的,首先,这可以做到吗?因为我找不到任何关于它的信息,其次,是否有更好的方法来显示数据而不会溢出?

感谢阅读本文

编辑:添加了一些示例地址和子网以反射(reflect)列表中可能包含的内容。

最佳答案

如果您有更多的 ips (10+),则更适合先将它们存储到 excel 中某处的列中,然后使用它们的范围作为数据验证“源”,即公式 1。

from openpyxl import Workbook
from openpyxl.worksheet.datavalidation import DataValidation

wb = Workbook()

ws = wb.create_sheet('New Sheet')

for number in range(1,100): #Generates 99 "ip" address in the Column A;
ws['A{}'.format(number)].value= "192.168.1.{}".format(number)

data_val = DataValidation(type="list",formula1='=$A:$A') #You can change =$A:$A with a smaller range like =A1:A9
ws.add_data_validation(data_val)

data_val.add(ws["B1"]) #If you go to the cell B1 you will find a drop down list with all the values from the column A

wb.save('Test.xlsx')

更多信息在这里:https://openpyxl.readthedocs.io/en/2.5/validation.html

关于python - OpenPyXL:是否可以在 Excel 工作表中创建下拉菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51497731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com