1. 程式人生 > >python使用xlrd讀取excel資料作為requests的請求引數,並把返回的資料寫入excel中

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是最新的。