使用 Apps 脚本以 Excel 格式将 Google Sheet 导出到 Google Drive

Eri*_*ika 1 export-to-excel google-sheets google-apps-script google-sheets-macros

我想将我的 Google 电子表格的备份创建到我的 Google Drive 文件夹中,但作为 Excel 文件。我设法创建了一个代码来创建 gsheet 的副本并将其保存到文件夹中,但我无法更改代码以将其保存为 Excel 文件。

你能帮我吗?

function makeCopy() {
  var formattedDate = Utilities.formatDate(new Date(), "CET", "yyyy-MM-dd' 'HH:mm");
  var name = "Backup Copy " + formattedDate;
  var destination = DriveApp.getFolderById("1vFL98cgKdMHLNLSc542pUt4FMRTthUvL");
  var file = DriveApp.getFileById("2SqIXLiic6-gjI2KwQ6OIgb-erbl3xqzohRgE06bfj2c")
  file.makeCopy(name, destination);
}
Run Code Online (Sandbox Code Playgroud)

Tan*_*ike 6

这个答案怎么样?我认为对于您的情况有几种答案。因此,请将此视为其中之一。

为了将电子表格转换为excel,https://docs.google.com/spreadsheets/d/" + sheetId + "/export?format=xlsx可以使用端点。在这个答案中,使用了这个。

修改后的脚本:

function makeCopy() {
  var formattedDate = Utilities.formatDate(new Date(), "CET", "yyyy-MM-dd' 'HH:mm");
  var name = "Backup Copy " + formattedDate;
  var destination = DriveApp.getFolderById("1vFL98cgKdMHLNLSc542pUt4FMRTthUvL");

  // Added
  var sheetId = "2SqIXLiic6-gjI2KwQ6OIgb-erbl3xqzohRgE06bfj2c";
  var url = "https://docs.google.com/spreadsheets/d/" + sheetId + "/export?format=xlsx&access_token=" + ScriptApp.getOAuthToken();
  var blob = UrlFetchApp.fetch(url).getBlob().setName(name + ".xlsx"); // Modified
  destination.createFile(blob);
}
Run Code Online (Sandbox Code Playgroud)

如果我误解了你的问题,我很抱歉。

更新时间:2020 年 2 月 7 日

从 2020 年 1 月起,访问令牌不能与查询参数一起使用,如access_token=###Ref所以请使用访问令牌到请求头而不是查询参数。如下。

var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
Run Code Online (Sandbox Code Playgroud)