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

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

首先需要导入三个包。
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")

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/718223.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存