Python với Excel và Google sheets tạo 'server database online' miễn phí

Liên hệ QC

befaint

|||||||||||||
Tham gia
6/1/11
Bài viết
14,347
Được thích
19,292
218606

Bài này sẽ giới thiệu một cách kết hợp Python, MS Excel, Google sheets để tạo 'server database online' miễn phí, cho phép đẩy dữ liệu từ Excel lên Google sheets để lưu trữ online, và lấy dữ liệu từ Google sheets xuống bảng tính Excel để làm gì đó theo mong muốn..

1/ Các công cụ:
- Python 3.x cài trên Windows (hoặc Mac)
- Thư viện gspread cho Python.
- Google Sheets API v4. Để sử dụng Google Sheets API trên Python cần thư viện oauth2client (kèm gói hỗ trợ PyOpenSSL).
* Cài đặt các thư viện gspread, oauth2client, PyOpenSSL:
PHP:
#install for Python 3.x
#Mac:
sudo python3 -m pip install PyOpenSSL
sudo python3 -m pip install --upgrade oauth2client
sudo python3 -m pip install gspread
#Windows:
py -m pip install PyOpenSSL
py -m pip install --upgrade oauth2client
py -m pip install gspread
* Cài đặt Google Sheets API v4
- Vào trang Google Developers Console tạo mới một project (đăng nhập bằng tài khoản Google).

218607
218610

Tiếp đó, vào mục Library, tìm Google sheets và kích hoạt API

218608
218609

218612

Tiếp theo, vào mục Credentials, tạo một "Service account key"..

218613
218614
218615
218616

Kết quả, tải một file key.json về máy tính, có nội dung như hình dưới.

218618

(Xem tiếp bài sau..)
 
Lần chỉnh sửa cuối:
{tiếp}

Đăng nhập vào Google sheets, tạo một trang tính mới (đặt tên, chọn nơi lưu trữ trên Google Drive...)

Click vào mục Share (ở góc trên phải), và nhập vào địa chỉ client_email lấy từ trong file key.json tải được ở bước cài đặt Google Sheets API để thiết lập chia sẻ bảng tính cho client_email đó, click nút Send để thực hiện.
Sau đó, chép lại File_ID cho bước sau.
219579


2/ Upload dữ liệu lên Google Sheets
Mục này, ta làm một ví dụ đơn giản: Điền số thứ tự 1-100 vào A1:A100.
Code Python như sau:
PHP:
import gspread, os, json
from oauth2client.service_account import ServiceAccountCredentials

file_api_key = "api_gsheets.json"
file_id = "1fX7a3J1H1Mit0-IBQeygKh2GuT7hy7A2mX..."

def get_json_file(file_path):
  json_file = open(file_path, 'r', encoding='utf-8')
  json_content = json.load(json_file)
  json_file.close()
  return json_content

def write_data_2range(worksheet, range_upload):
  """ ví dụ đơn giản - điền số 1,2,3.. vào range_upload
  worksheet - google sheets
  range_upload - một range của worksheet
  """
  i = 1
  for cell in range_upload: # ghi dữ liệu vào từng cell của range_upload
     cell.value = i
     i += 1
  worksheet.update_cells(range_upload) # cập nhật dữ liệu đã ghi 

def upload_data(file_id_):
  top_path = os.path.dirname(os.path.abspath(__file__))
  keyfile_path = os.path.join(top_path, file_api_key)
  keyfile_dict = get_json_file(keyfile_path)
  scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
  try: 
    credentials = ServiceAccountCredentials.from_json_keyfile_dict(keyfile_dict, scope)
    gc = gspread.authorize(credentials)
    worksheet = gc.open_by_key(file_id_).sheet1
    range_upload = worksheet.range('A1:A100')
    write_data_2range(worksheet,range_upload)
    print("Done!")
  except:
    print("Error!")

# run 
upload_data(file_id)
Mở file python-gsheets.py bằng IDLE Python rồi Run module.
Xem video:


(Xem tiếp bài sau - Lấy dữ liệu từ file Excel đẩy lên Google sheets..)
 

File đính kèm

  • python-gsheets.zip
    3 KB · Đọc: 56
Lần chỉnh sửa cuối:
Upvote 0
Bài này hay quá anh, hóng tiếp bài sau ạ.
 
Upvote 0
Bài từ 2019 mà chưa có bài tiếp theo. chắc hóng cũng không có đâu
 
Lần chỉnh sửa cuối:
Upvote 0
Share tiếp đi anh
{tiếp}

Đăng nhập vào Google sheets, tạo một trang tính mới (đặt tên, chọn nơi lưu trữ trên Google Drive...)

Click vào mục Share (ở góc trên phải), và nhập vào địa chỉ client_email lấy từ trong file key.json tải được ở bước cài đặt Google Sheets API để thiết lập chia sẻ bảng tính cho client_email đó, click nút Send để thực hiện.
Sau đó, chép lại File_ID cho bước sau.
View attachment 219579


2/ Upload dữ liệu lên Google Sheets
Mục này, ta làm một ví dụ đơn giản: Điền số thứ tự 1-100 vào A1:A100.
Code Python như sau:
PHP:
import gspread, os, json
from oauth2client.service_account import ServiceAccountCredentials

file_api_key = "api_gsheets.json"
file_id = "1fX7a3J1H1Mit0-IBQeygKh2GuT7hy7A2mX..."

def get_json_file(file_path):
  json_file = open(file_path, 'r', encoding='utf-8')
  json_content = json.load(json_file)
  json_file.close()
  return json_content

def write_data_2range(worksheet, range_upload):
  """ ví dụ đơn giản - điền số 1,2,3.. vào range_upload
  worksheet - google sheets
  range_upload - một range của worksheet
  """
  i = 1
  for cell in range_upload: # ghi dữ liệu vào từng cell của range_upload
     cell.value = i
     i += 1
  worksheet.update_cells(range_upload) # cập nhật dữ liệu đã ghi

def upload_data(file_id_):
  top_path = os.path.dirname(os.path.abspath(__file__))
  keyfile_path = os.path.join(top_path, file_api_key)
  keyfile_dict = get_json_file(keyfile_path)
  scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
  try:
    credentials = ServiceAccountCredentials.from_json_keyfile_dict(keyfile_dict, scope)
    gc = gspread.authorize(credentials)
    worksheet = gc.open_by_key(file_id_).sheet1
    range_upload = worksheet.range('A1:A100')
    write_data_2range(worksheet,range_upload)
    print("Done!")
  except:
    print("Error!")

# run
upload_data(file_id)
Mở file python-gsheets.py bằng IDLE Python rồi Run module.
Xem video:


(Xem tiếp bài sau - Lấy dữ liệu từ file Excel đẩy lên Google sheets..)
 
Upvote 0
Web KT
Back
Top Bottom