You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何将Python程序输出的JSON数据导入Google Sheets?

Hey there! Since you're already comfortable with Python, let's focus on solutions that leverage your existing skills instead of hunting down third-party storage services. Here are three practical ways to get your JSON data into Google Sheets:

This is the most seamless approach—you can modify your existing Python program to send JSON data straight to Sheets using the Google Sheets API. Here's how to set it up:

Step 1: Set Up Google Cloud Credentials

  • Go to the Google Cloud Console, create a new project, and enable the Google Sheets API.
  • Create a service account, download its JSON key file, and save it in your project folder.
  • Share your target Google Sheet with the service account's email address (found in the key file) to grant write access.

Step 2: Install Required Libraries

pip install google-api-python-client oauth2client

Step 3: Python Code to Import JSON

Adjust this snippet to match your JSON structure (example assumes your JSON is a list of dictionaries):

import json
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# Load your JSON data
with open("your_output.json", "r") as f:
    json_data = json.load(f)

# Convert JSON to a 2D array (compatible with Google Sheets)
# First row = headers, subsequent rows = data values
sheet_rows = [list(json_data[0].keys())]
for entry in json_data:
    sheet_rows.append(list(entry.values()))

# Authenticate with Google Sheets API
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
SERVICE_ACCOUNT_KEY = "path-to-your-service-account-key.json"
creds = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_KEY, SCOPES)
service = build("sheets", "v4", credentials=creds)

# Write data to your sheet
SPREADSHEET_ID = "your-sheet-id-here"  # Grab this from your Sheet's URL
RANGE = "Sheet1!A1"  # Starting cell for your data

update_request = service.spreadsheets().values().update(
    spreadsheetId=SPREADSHEET_ID,
    range=RANGE,
    valueInputOption="RAW",
    body={"values": sheet_rows}
)
response = update_request.execute()

print(f"Success! Updated {response['updatedCells']} cells.")
2. Convert JSON to CSV (Quick & Manual)

If you prefer a simpler, non-automated route, convert your JSON to CSV first—Google Sheets supports direct CSV uploads. Python makes this trivial:

import json
import csv

with open("your_output.json", "r") as f:
    json_data = json.load(f)

# Write to CSV
with open("output.csv", "w", newline="") as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=json_data[0].keys())
    writer.writeheader()
    writer.writerows(json_data)

Once you have the CSV file, just drag-and-drop it into Google Sheets, or use the "File > Import" option to load it into your target sheet.

3. Use Google Drive + Apps Script (Automated Sync)

If you still want to store your JSON online and sync it to Sheets, use Google Drive as storage and a small Apps Script to pull the data automatically:

  1. Upload your JSON file to Google Drive and note its file ID (from the share URL).
  2. Open your Google Sheet, go to Extensions > Apps Script.
  3. Replace the default code with this snippet (adjust file ID and sheet name as needed):
function syncJSONToSheet() {
  const jsonFileId = "your-json-file-id";
  const sheetName = "Sheet1";
  
  // Fetch JSON from Drive
  const file = DriveApp.getFileById(jsonFileId);
  const jsonString = file.getBlob().getDataAsString();
  const jsonData = JSON.parse(jsonString);
  
  // Clear existing data and write new content
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  sheet.clearContents();
  
  // Write headers
  const headers = Object.keys(jsonData[0]);
  sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
  
  // Write data rows
  const dataRows = jsonData.map(item => Object.values(item));
  sheet.getRange(2, 1, dataRows.length, dataRows[0].length).setValues(dataRows);
}
  1. Set up a time-driven trigger in Apps Script to run this function automatically (e.g., every hour) so your sheet stays in sync with the JSON file.

内容的提问来源于stack exchange,提问作者Keenan B

火山引擎 最新活动