首先需要导入三个包。
openpyxl,操作excel文件
requests,发送Web网络请求
json,处理json对象

import openpyxl
import requests
import json

如果包不能用的话,需要先安装它,如

pip install openpyxl

定义几个变量

# 提交时发送头信息
headers = {
    'Content-Type': 'application/json',
    'accept': 'text/plain'
}
file_excel = r'C:\Users\Zmrbak\Desktop\IP地址20220420.xlsx'
api_url = 'http://192.168.250.16/api/HostModels'

post 操作

def post_date(data):
	# 在提交的时候,需要发送头
    rep = requests.post(url=api_url, data=json.dumps(data), headers=headers)
    print(rep.status_code)
    # 这里对返回数据进行解码,否则会出现中文乱码问题
    print(rep.text.encode(rep.encoding).decode('utf-8'))

处理空值

# 处理空值(None)问题
def default_data(data, default_=None):
    if data is not None:
        return data
    else:
        return default_

解析Excel文件

def load_excel(file_):
	# 打开Excel文件
    wb = openpyxl.load_workbook(file_)
    # 读取其中一个表
    sheet = wb['IP地址使用登记']
    index = 0
    # 遍历所有行
    for row in sheet.iter_rows():
        index += 1
        # 第一行是标题,跳过
        if index == 1:
            continue

		# 第二列
        ip_inter = row[1].value
        ip_public = row[2].value
        host_name = row[3].value
        host_mac = row[4].value
        asset_number = row[5].value
        location = row[6].value
        usage = row[7].value

		# 第二列为空,则跳过
        if ip_inter is None:
            continue

		# 构造 POST的 Json数据
        input_data = {
        	# 如果是空值(None)的话,用空字符串替换
            "ipInAddress": "" + default_data(ip_inter, "") + "",
            "ipInMacAddress": "" + default_data(host_mac, "") + "",
            "ipOutAddress": "" + default_data(ip_public, "") + "",
            "hostName": "" + default_data(host_name, "") + "",
            "assetNumber": "" + default_data(asset_number, "") + "",
            "location": "" + default_data(location, "") + "",
            "usage": "" + default_data(usage, "") + "",
            "holder": "赵庆明"
        }
        post_date(input_data)

Get 请求

def get_all_data():
	# 发送一个 GET请求
    rep = requests.get(api_url)
    # 解码
    print(rep.text.encode(rep.encoding).decode('utf-8'))

执行程序

if __name__ == '__main__':
    # load_excel(file_excel)
    get_all_data()
    print("done")
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐