我正在尝试使用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地址放入下拉列表,因为这将更容易阅读 – 所以我的问题是双重的,首先,这可以做到吗?因为我找不到任何关于它的信息,其次,有没有更好的方法来显示数据而不会溢出?

感谢您阅读本文

编辑:添加了一些示例地址和子网,以反映列表中可能包含的内容.

解决方法:

如果你有更多的ips(10),那么最好先将它们存储到excel中的某个列中,然后使用它们的范围作为数据验证“Source”又名formula1.

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

标签:openpyxl,python

来源: https://codeday.me/bug/20190929/1832610.html

版权声明:本文为CSDN博主「weixin_39936086」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接: https://blog.csdn.net/weixin_39936086/article/details/110117291