我正在尝试使用 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 地址放入下拉列表中,因为这样会更容易阅读 - 所以我的问题是双重的,首先,这可以做到吗?因为我找不到任何有关它的信息,其次,是否有可能有更好的方法来显示数据而不溢出?
感谢您阅读本文
编辑:添加了一些示例地址和子网以反映列表中可能存在的内容。
如果您有大量 ip (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
# Create the list of options for the drop down:
list_each = ['EA', 'KIT']
# Create the data validation rules we want to add:
dv_list_each = DataValidation(type="list", formula1=f'"{",".join(list_each)}"', showDropDown=False, allow_blank=True) # To see the drop down arrow, use "showDropDown=False"