python使用xlrd读取excel数据作为requests的请求参数,并把返回的数据写入excel中

实现功能:

从excel中的第一列数据作为post请求的数据,数据为json格式;把post返回的结果写入到excel的第二列数据中

每一行的数据都不一样,可实现循环调用

# !/usr/bin/env python
# -*- coding:utf-8 -*-
#import xlwt #这个专门用于写入excel的库没有用到
import xlrd
from xlutils.copy import copy
import requests
import json
old_excel = xlrd.open_workbook('excel.xls')
sheet = old_excel.sheets()[0]
url = 'http://10.1.1.32:1380/service/allocFk2'
headers = {'Content-Type': 'application/json'}
i = 0
new_excel = copy(old_excel)
for row in sheet.get_rows():
    data = row[0].value
    response = requests.post(url=url, headers=headers, data=data)
    text = response.text
    #使用json.loads可以把Unicode类型,即json类型转换成dict类型
    text = json.loads(text)["returnMsg"] #屏蔽这行代码即可把返回的完整数据写入文件中
    ws = new_excel.get_sheet(0)
    ws.write(i,1,text)
    new_excel.save('excel.xls')
    old_excel = xlrd.open_workbook('excel.xls')
    new_excel = copy(old_excel)
    i = i+1

结果: 

(一开始的excel.xls只有第一列数据,执行成功以后才会有第二列数据)

{
   "projectId" :"0070",
   "projectAllocBatch" :"1",
   "serviceCode" :"GT012",
   "seqNo" :"180800272201GT51286712",
   "tranTimeStamp" :"20180817102244",
   "sign" :"2dbb89a6bd86b2af1ff6a76c35c05284"
}
{"sign":"d7f3a72adb2d0517c94af22f9aaa0712","returnCode":"00001","tranTimeStamp":"20180817102244","seqNo":"180800272201GT51286712","returnMsg":"交易失败","serviceCode":"GT012"}
{
   "projectId" :"0070",
   "projectAllocBatch" :"1",
   "serviceCode" :"GT012",
   "seqNo" :"180800272201GT51286713",
   "tranTimeStamp" :"20180817102244",
   "sign" :"2dbb89a6bd86b2af1ff6a76c35c05284"
}
{"sign":"c107bb75e717ad589c913294b340aca8","returnCode":"00001","tranTimeStamp":"20180817102244","seqNo":"180800272201GT51286713","returnMsg":"交易失败","serviceCode":"GT012"}
{
   "projectId" :"0070",
   "projectAllocBatch" :"1",
   "serviceCode" :"GT012",
   "seqNo" :"180800272201GT51286713",
   "tranTimeStamp" :"20180817102244",
   "sign" :"2dbb89a6bd86b2af1ff6a76c35c05284"
}
{"sign":"c107bb75e717ad589c913294b340aca8","returnCode":"00001","tranTimeStamp":"20180817102244","seqNo":"180800272201GT51286713","returnMsg":"交易失败","serviceCode":"GT012"}

调试过程中遇到的问题:

一开始在for循环的最后没有增加这两行代码

old_excel = xlrd.open_workbook('excel.xls')
new_excel = copy(old_excel)

这样的话new_excel永远都是一开始获取到的那一个,只会把最后一个循环返回的结果写入文件,因为之前的全部都被一开始获取的那个old_excel给覆盖了,所以每次执行完写入操作以后都要重新做一次copy操作,这样就能保证new_excel是最新的。

猜你喜欢

转载自blog.csdn.net/baidu_30374343/article/details/85134306