使用Google脚本将Google表格导出到Excel中

时间:2018-07-04 15:53:50

标签: excel google-sheets-api

我正在尝试将Google表格的备份自动转换为Excel。

尝试了Stackoverflow上出现的不同脚本后,我现在正在运行的脚本没有任何反应。

有什么想法吗?

代码如下:

function exportAsxlsx() {
  var spreadsheet   = SpreadsheetApp.getActiveSpreadsheet();
  var spreadsheetId = spreadsheet.getId()
  var file = DriveApp.getFileById(spreadsheetId)

  var url           = 'https://docs.google.com/spreadsheets/d/'+spreadsheetId+'/export?format=xlsx';
  var token         = ScriptApp.getOAuthToken();
  var response      = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });

  var blobs   = response.getBlob();
  var folder = DriveApp.getFoldersByName('Exports');
  if(folder.hasNext()) {
    var existingPlan1 = DriveApp.getFilesByName('newfile.xlsx');
    if(existingPlan1.hasNext()){
      var existingPlan2 = existingPlan1.next();
      var existingPlanID = existingPlan2.getId();
      Drive.Files.remove(existingPlanID);
    }
  } else {
    folder = DriveApp.createFolder('BackUp');
  }
  folder = DriveApp.getFoldersByName('BackUp').next();
  var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd' 'HH:mm:ss");
  var name = SpreadsheetApp.getActiveSpreadsheet().getName() + " Copy " + formattedDate;
  folder.createFile(blobs).setName(name + '.xlsx')
}

1 个答案:

答案 0 :(得分:1)

因此,这是一个有效的脚本:

function exportAsxlsx() {
  var spreadsheet   = SpreadsheetApp.getActiveSpreadsheet();
  var spreadsheetId = spreadsheet.getId()
  var file = DriveApp.getFileById(spreadsheetId)

  var url           = 'https://docs.google.com/spreadsheets/d/'+spreadsheetId+'/export?format=xlsx';
  var token         = ScriptApp.getOAuthToken();
  var response      = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });

  var blobs   = response.getBlob();
  var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd' 'HH:mm:ss");
  var name = SpreadsheetApp.getActiveSpreadsheet().getName() + " Copy " + formattedDate;
  var folder = DriveApp.getFolderById("your folder ID");
  folder.createFile(blobs).setName(name + '.xlsx');
}