Google Sheets API是Google提供的一套编程接口,允许开发者以编程方式读取、写入和修改Google电子表格中的数据。通过API创建第一行通常涉及向指定工作表发送数据插入请求。
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
# 初始化凭据(需替换为你的实际凭据)
creds = Credentials.from_authorized_user_file('token.json', ['https://www.googleapis.com/auth/spreadsheets'])
# 创建服务对象
service = build('sheets', 'v4', credentials=creds)
# 电子表格ID和工作表名称
spreadsheet_id = '你的电子表格ID'
sheet_name = 'Sheet1' # 或你的工作表名称
# 要插入的数据(第一行)
values = [
['列1标题', '列2标题', '列3标题'] # 替换为你需要的列标题
]
# 请求体
body = {
'values': values
}
# 调用API插入数据
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheet_id,
range=f"{sheet_name}!A1", # 从A1单元格开始
valueInputOption='USER_ENTERED',
body=body
).execute()
print(f"已更新 {result.get('updatedCells')} 个单元格")
const {google} = require('googleapis');
async function addFirstRow(auth) {
const sheets = google.sheets({version: 'v4', auth});
const spreadsheetId = '你的电子表格ID';
const range = 'Sheet1!A1:C1'; // 根据你的列数调整
const values = [
['列1标题', '列2标题', '列3标题']
];
const resource = {
values,
};
try {
const result = await sheets.spreadsheets.values.update({
spreadsheetId,
range,
valueInputOption: 'USER_ENTERED',
resource,
});
console.log(`${result.data.updatedCells} cells updated.`);
} catch (err) {
console.error('API错误:', err);
}
}
https://www.googleapis.com/auth/spreadsheets
USER_ENTERED
选项可以保留数据格式没有搜到相关的文章