程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | import requests import json from openpyxl import Workbook from openpyxl.chart import BarChart, Reference from openpyxl.utils import get_column_letter # 從URL取得JSON資料 r = requests.get('https://data.moa.gov.tw/Service/OpenData/FromM/AquaticTransData.aspx') json_data = json.loads(r.text) # 建立Workbook wb = Workbook() ws = wb.active ws.title = "斗南田蛙交易" # 寫入標題行 headers = ['交易日期', '品種代碼', '魚貨名稱', '市場名稱', '交易量', '平均價'] ws.append(headers) # 過濾出「斗南」市場的「田蛙」資料 for item in json_data: if '田蛙' in item['魚貨名稱'] and '斗南' in item['市場名稱']: row = [ item.get('交易日期'), item.get('品種代碼'), item.get('魚貨名稱'), item.get('市場名稱'), float(item.get('交易量', 0)), float(item.get('平均價', 0)) ] ws.append(row) # 取得資料列數 data_rows = ws.max_row # 建立長條圖(交易量) chart = BarChart() chart.title = "田蛙在斗南市場之交易量" chart.x_axis.title = "交易日期" chart.y_axis.title = "交易量" # 設定圖表資料範圍(x軸是日期,y軸是交易量) data = Reference(ws, min_col=5, min_row=1, max_row=data_rows) # 交易量資料 categories = Reference(ws, min_col=1, min_row=2, max_row=data_rows) # 交易日期 chart.add_data(data, titles_from_data=True) chart.set_categories(categories) # 插入圖表到工作表 ws.add_chart(chart, "H2") # 儲存檔案 wb.save("DouNan_TianWa_Chart.xlsx") print("已完成:含圖表的 Excel 已儲存為 DouNan_TianWa_Chart.xlsx") |
執行結果如文章一開始顯示的圖表。
沒有留言:
張貼留言