今天給大家介紹一個Python+Excel的實戰專案,非常有趣, 主要使用xlwings和requests這兩個Python庫,以及Office的Excel,xlwings處理表格,requests則是請求資料, 先從Excel中獲取城市資訊,然后請求介面,獲取到天氣資訊,再回傳給Excel,
具體操作可以看下圖,文末提供進群技術討論群,歡迎加入

在城市欄輸入杭州,點擊查詢按鈕,表格的資料就會發生變化,的確是杭州的天氣預報,
① 資料獲取
既然是天氣預報,那肯定是需要天氣資料的,
找了一圈國內開放的天氣API介面,大多都是需要注冊,果斷放棄,
騰訊倒是有個不錯的,可惜介面資訊不太完整,沒有相應的資料說明,
地址:https://tianqi.qq.com/
介面地址:https://wis.qq.com/weather/common

最終選擇了一個國外的天氣API介面,
地址:https://www.metaweather.com/zh/

并沒有提供國內所有的城市,目前只有10個城市,
所以要想城市多一些,騰訊的天氣介面還是可以考慮的,
一共是有10種天氣狀態,并且提供了相關的天氣狀態圖片,可以供我們使用,
圖片已經下載下來了,需要的小伙伴可以文末獲取哦!

首先通過查詢,獲取城市的ID值,

然后根據ID值,再去獲取對應的天氣資訊,

相關名稱的中英文對照如下,
# 天氣--中英文名對照
weather = {
'Snow': '雪',
'Sleet': '雨夾雪',
'Hail': '冰雹',
'Thunderstorm': '雷陣雨',
'Heavy Rain': '大雨',
'Light Rain': '小雨',
'Showers': '陣雨',
'Heavy Cloud': '陰',
'Light Cloud': '多云',
'Clear': '晴'
}
# 城市--中英文名對照
citys = {
'北京': 'Beijing',
'成都': 'Chengdu',
'東莞': 'Dongguan',
'廣州': 'Guangzhou',
'杭州': 'Hangzhou',
'香港': 'Hong Kong',
'上海': 'Shanghai',
'深圳': 'Shenzhen',
'天津': 'Tianjin',
'武漢': 'Wuhan'
}
② 創建表格
安裝xlwings庫,并且使用命令列創建專案,
# 安裝xlwings
pip install xlwings -i https://mirror.baidu.com/pypi/simple/
# 命令列運行
xlwings quickstart weatherapp --standalone
如此便會生成兩個檔案,Python和Excel檔案,

其中weatherapp.py的檔案內容如下,
import xlwings as xw
def main():
wb = xw.Book.caller()
sheet = wb.sheets[0]
if sheet["A1"].value == "Hello xlwings!":
sheet["A1"].value = "Bye xlwings!"
else:
sheet["A1"].value = "Hello xlwings!"
if __name__ == "__main__":
xw.Book("weatherapp.xlsm").set_mock_caller()
main()
而Excel是什么內容也沒有的,打開時會提示是否啟用宏,選擇是,
然后需要將Excel的開發工具打開,后面會使用它插入一些元素,

上圖為Mac電腦的設定,Windows電腦設定起來也很簡單,具體可以百度,
通過點擊開發工具選項,我們可以使用Excle的Visual Basic 編輯器(VBA),還能插入按鈕(查詢按鈕),

然后我在表格中插入一個點擊按鈕,

選擇宏名稱為SampleCall,宏的位置為當前作業簿,

點擊按鈕1,A1單元格出現內容Hello xlwings!,

再次點擊,A1單元格內容變為Bye xlwings!,

也就意味著,修改weatherapp.py檔案的代碼,即可實作Excel的互動操作,
下面對表格進行頁面設計,畢竟要讓表格好看起來,

設定表格的行高、列寬、背景色、固定文字內容等資訊,
將單元格C3名稱設定為city_name,插入6張太陽圖片,排列在單元格C9~H9處,居中對齊,圖片也改名為no.1~no.6,
修改weatherapp.py檔案代碼如下,
import json
from pathlib import Path
import requests
import xlwings as xw
# 天氣--中英文名對照
weather = {
'Snow': '雪',
'Sleet': '雨夾雪',
'Hail': '冰雹',
'Thunderstorm': '雷陣雨',
'Heavy Rain': '大雨',
'Light Rain': '小雨',
'Showers': '陣雨',
'Heavy Cloud': '陰',
'Light Cloud': '多云',
'Clear': '晴'
}
# 城市--中英文名對照
citys = {
'北京': 'Beijing',
'成都': 'Chengdu',
'東莞': 'Dongguan',
'廣州': 'Guangzhou',
'杭州': 'Hangzhou',
'香港': 'Hong Kong',
'上海': 'Shanghai',
'深圳': 'Shenzhen',
'天津': 'Tianjin',
'武漢': 'Wuhan'
}
def main():
# 通過runpython從excel中呼叫python函式
wb = xw.Book.caller()
sht = wb.sheets[0]
# 從Excel中讀取城市資訊
city_name = citys[sht.range("city_name").value]
# 獲取城市的ID值, 即woeid
URL_CITY = f"https://www.metaweather.com/api/location/search/?query={city_name}"
response_city = requests.request("GET", URL_CITY)
city_title = json.loads(response_city.text)[0]["title"]
city_id = json.loads(response_city.text)[0]["woeid"]
# 獲取城市的天氣資訊
URL_WEATHER = f"https://www.metaweather.com/api/location/{city_id}/"
response_weather = requests.request("GET", URL_WEATHER)
weather_data = json.loads(response_weather.text)["consolidated_weather"]
# 創建空串列, 存盤資料
min_temp = []
max_temp = []
weather_state_name = []
weather_state_abbr = []
applicable_date = []
# 處理資料
for index, day in enumerate(weather_data):
# 最低溫度
min_temp.append(weather_data[index]["min_temp"])
# 最高溫度
max_temp.append(weather_data[index]["max_temp"])
# 天氣情況
weather_state_name.append(weather[weather_data[index]["weather_state_name"]])
# 天氣情況縮寫
weather_state_abbr.append(weather_data[index]["weather_state_abbr"])
# 日期
applicable_date.append(weather_data[index]["applicable_date"])
# 將獲取到的值填充到Excel中
sht.range("C5").value = applicable_date
sht.range("C6").value = weather_state_name
sht.range("C7").value = max_temp
sht.range("C8").value = min_temp
sht.range("D3").value = city_title
# 創建串列
icon_names = ["no.1", "no.2", "no.3", "no.4", "no.5", "no.6"]
# 設定天氣圖片路徑
icon_path = Path(__file__).parent / "images"
# 將天氣情況與天氣圖片進行匹配,更新表格
for icon, abbr in zip(icon_names, weather_state_abbr):
image_path = Path(icon_path, abbr + ".png")
sht.pictures.add(image_path, name=icon, update=True)
if __name__ == "__main__":
# 設定用于除錯caller()的excel檔案,可以直接在python里運行
xw.Book("weatherapp.xlsm").set_mock_caller()
main()
此時我們打開Excel表格,在城市欄輸入10個城市中的一個,然后點擊查詢按鈕,天氣就會更新,

好了,本期的分享就到此結束了,有興趣的小伙伴可以自行去實踐學習,
技術交流
歡迎轉載、收藏、有所識訓點贊支持一下!

目前開通了技術交流群,群友已超過2000人,添加時最好的備注方式為:來源+興趣方向,方便找到志同道合的朋友
- 方式①、發送如下圖片至微信,長按識別,后臺回復:加群;
- 方式②、添加微信號:dkl88191,備注:來自CSDN
- 方式③、微信搜索公眾號:Python學習與資料挖掘,后臺回復:加群

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/309520.html
標籤:python
