如何使用 Google Drive API 创建电子表格文件,并将默认选项卡标题设置为“Sheet1”以外的其他内容

Dir*_*dNJ 5 google-sheets node.js google-drive-api google-sheets-api

我想通过 google Drive(v3) API 创建电子表格,其中:

  1. 我上传 CSV 数据来填充第一个选项卡
  2. 我可以将选项卡的名称设置为“Sheet1”以外的名称

我花了一整夜的时间爬行 Google API for Sheets(v4) 和 Drive(v3),但仍然无法弄清楚这个!

如果我不能这样做,似乎我将不得不发送额外的请求来更新工作表属性,以在完成初始上传后更改标题。如果可能的话,我想避免这种情况,但我意识到这可能是唯一的方法。

这是我发送的 API 请求:

let fileMetadata = {
  name: name,
  title: 'rawData', //This does NOT get set! Tab appears as "Sheet1"
  mimeType: 'application/vnd.google-apps.spreadsheet'
}

let media = {
  mimeType: 'text/csv',
  body: data // The body data is the raw parsed CSV
}

var Google = google.drive('v3')
Google.files.create({
  auth: auth,
  media: media,
  resource: fileMetadata
}, function(err, response) {
  if (err) {
    console.log('The API returned an error: ' + err)
    return done(err)
  } else {

    console.log('success!')
    console.log(response)

  }

})
Run Code Online (Sandbox Code Playgroud)

Mr.*_*bot 4

我尝试使用Sheet API创建一个新的电子表格,然后使用 Method: spreadsheets.create。使用 Sheets API 等特定 API 为您提供更多专业方法,例如添加工作表标题属性(更多工作表特定方法)。

创建电子表格,返回新创建的电子表格。

// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Google Sheets API
//    and check the quota for your project at
//    https://console.developers.google.com/apis/api/sheets
// 2. Install the Node.js client library by running
//    `npm install googleapis --save`

var google = require('googleapis');
var sheets = google.sheets('v4');

authorize(function(authClient) {
  var request = {
    resource: {
      // TODO: Add desired properties to the request body.
    },

    auth: authClient
  };

  sheets.spreadsheets.create(request, function(err, response) {
    if (err) {
      console.log(err);
      return;
    }

    // TODO: Change code below to process the `response` object:
    console.log(JSON.stringify(response, null, 2));
  });
});

function authorize(callback) {
  // TODO: Change placeholder below to generate authentication credentials. See
  // https://developers.google.com/sheets/quickstart/nodejs#step_3_set_up_the_sample
  //
  // Authorize using one of the following scopes:
  //   'https://www.googleapis.com/auth/drive'
  //   'https://www.googleapis.com/auth/spreadsheets'
  var authClient = null;

  if (authClient == null) {
    console.log('authentication failed');
    return;
  }
  callback(authClient);
}
Run Code Online (Sandbox Code Playgroud)

我使用了尝试这个 API 在此输入图像描述

结果是:

在此输入图像描述

这也将位于您的 Google 云端硬盘中。

希望这可以帮助。