【原创】Python读取EXEL文件,POST、GET和中文解码

首先需要导入三个包。
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")
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵庆明老师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值