befaint
|||||||||||||
- Tham gia
- 6/1/11
- Bài viết
- 14,540
- Được thích
- 19,749
*
Hôm lâu lâu có lướt qua trang chủ thấy bài viết nổi bật này: Import chuỗi JSON vào Excel (1)
Mình cũng thử góp thêm một cách sử dụng Python.
Xem bài viết Python với Excel - Mở đầu và cài đặt thư viện để cài đặt Python và thư viện cần thiết.
Nội dung bài này: Xuất dữ liệu JSON (dạng file đã có trên ổ đĩa, từ đường dẫn trên internet)
Trường hợp lấy dữ liệu JSON từ đường dẫn trên internet cần cài đặt thêm module requests
Theo nội dung ở bài viết (1), xin phép mượn đường dẫn (link_json) và file dữ liệu json trong bài #54 của bài viết trên làm căn cứ để viết trên Python.
** Viết code xử lý
Ở chủ đề (1) thấy có cả lấy dữ liệu từ url, và từ file trên ổ đĩa nên mình cũng viết luôn 2 phần. Mới đọc Python một chút nên code dùng tạm..
Sử dụng:
Tải file bên dưới, giải nén, click phải chuột vào file json2Excel.py rồi chọn Edit with IDLE...
Cửa sổ IDLE Python hiện ra thì nhấn F5 để chạy code (hoặc vào Run menu, chọn Run Module).
*****
Chạy thử code VBA trong bài #54 ở chủ đề (1):
.
Chạy thử code Python: Chẳng hiểu sao nó chạy nhanh thế, bao gồm tạo workbook, xử lý dữ liệu và ghi file lên ổ đĩa..
Hôm lâu lâu có lướt qua trang chủ thấy bài viết nổi bật này: Import chuỗi JSON vào Excel (1)
Mình cũng thử góp thêm một cách sử dụng Python.
Xem bài viết Python với Excel - Mở đầu và cài đặt thư viện để cài đặt Python và thư viện cần thiết.
Nội dung bài này: Xuất dữ liệu JSON (dạng file đã có trên ổ đĩa, từ đường dẫn trên internet)
Trường hợp lấy dữ liệu JSON từ đường dẫn trên internet cần cài đặt thêm module requests
Mã:
py -m pip install requests
Theo nội dung ở bài viết (1), xin phép mượn đường dẫn (link_json) và file dữ liệu json trong bài #54 của bài viết trên làm căn cứ để viết trên Python.
** Viết code xử lý
Ở chủ đề (1) thấy có cả lấy dữ liệu từ url, và từ file trên ổ đĩa nên mình cũng viết luôn 2 phần. Mới đọc Python một chút nên code dùng tạm..
Python:
from openpyxl import Workbook
import json, requests
import time, os
""" get data from json file """
def getJsonFile(file_path):
try:
json_file = open(file_path, 'r', encoding='utf-8')
json_data = json.load(json_file)
except:
json_file = open(file_path, 'r', encoding='utf-8-sig')
json_data = json.load(json_file)
json_file.close()
return json_data
""" get data json from url """
def getJsonUrl(url_):
json_data = ""
req = requests.get(url_)
if req.status_code == 200:
json_data = req.json()
else:
json_data = ""
return json_data
""" import json data to Excel """
def Json_to_Excel(json_data, excel_file_):
""" type(json_data) == <class 'dict'>
excel_file_ = path of excel file
"""
const_key = "payload"
if isinstance(json_data, dict) == True:
data_payload = json_data.get(const_key)
# get keys from first item of 'data_payload'
keys_list=[]
item0 = list(data_payload[0].keys())
for key in item0:
keys_list.append(key)
# create a new Excel workbook
wb = Workbook()
ws = wb.active
# write header to worksheet
ws.append(keys_list)
# get all data in data_payload and write to worksheet
res_payload = []
for item_data in data_payload:
for skey in keys_list:
# get value by key
value = item_data.get(skey)
if isinstance(value, list) == True:
value = " ".join(value)
res_payload.append(value)
ws.append(res_payload)
res_payload.clear()
# save workbook
wb.save(excel_file_)
else:
print("Nothing data to import...")
""" get data from json file """
def main_json_file(json_file_name, excel_file):
# get path file
top_path = os.path.dirname(os.path.abspath(__file__))
excel_file = os.path.join(top_path, excel_file)
json_file_path = os.path.join(top_path, json_file_name)
json_data = getJsonFile(json_file_path)
Json_to_Excel(json_data, excel_file)
""" get data from json url """
def main_json_url(url, excel_file):
# get path file
top_path = os.path.dirname(os.path.abspath(__file__))
excel_file = os.path.join(top_path, excel_file)
json_data = getJsonUrl(url)
Json_to_Excel(json_data, excel_file)
# run use json file
time_start = time.time()
excel_file = "excel_json.xlsx" # tên tập tin Excel chứa kết quả đặt cùng thư mục với json2Excel.py
json_file_name = "json_data.json" # tên tập tin json cần xử lý đặt cùng thư mục với json2Excel.py
main_json_file(json_file_name, excel_file)
print(time.time()-time_start)
# run use json url. Remove mark """ to run it
"""
time_start = time.time()
excel_file = "excel_json.xlsx" # tên tập tin Excel chứa kết quả đặt cùng thư mục với json2Excel.py
# link - đường dẫn chứa json data
link = "https://syndication.redplum.com/kilgore/StandardSyndicationPartner/offers/?provider=thor&filterByZipCode=77477&filterByLoyaltyProgram=all"
main_json_url(link, excel_file)
print(time.time()-time_start)
"""
Sử dụng:
Tải file bên dưới, giải nén, click phải chuột vào file json2Excel.py rồi chọn Edit with IDLE...
Cửa sổ IDLE Python hiện ra thì nhấn F5 để chạy code (hoặc vào Run menu, chọn Run Module).
*****
Chạy thử code VBA trong bài #54 ở chủ đề (1):
.
Chạy thử code Python: Chẳng hiểu sao nó chạy nhanh thế, bao gồm tạo workbook, xử lý dữ liệu và ghi file lên ổ đĩa..
File đính kèm
Lần chỉnh sửa cuối: