Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google apps script - How do I make copy of spreadsheet and save it to particular folder?

I'm working with Google App Script. I am trying to:

  1. Make a copy of a spreadsheet
  2. Give the copy a particular file name, and
  3. Save it to a particular folder.

It seems to me that the code below should work, but it doesn't. It does accomplish tasks 1 and 3 - that is, it makes a copy and saves the copy to my desired folder. However, it does not save the file with the file name I specify. Instead, it saves it as "Copy of [original spreadsheet filename]." To do this, I am using File#makeCopy

(Note: I know this question has been answered before, but I believe it has not been answered since Google sunset the DocList service.)

When I made this simplified MCVE, I found that it works as expected:

function saveAsSpreadsheet() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxx");
  DriveApp.getFileById(sheet.getId()).makeCopy("desired file name", destFolder);
} //END function saveAsSpreadsheet

However, my original code does not - the copy's name is wrong:

function saveAsSpreadsheet() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var buildingNameAddress = sheet.getRangeByName('buildingNameAddress').getValue();
  Logger.log(buildingNameAddress); //Logs correct string
  var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxxxx");
  DriveApp.getFileById(sheet.getId()).makeCopy(buildingNameAddress, destFolder);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the corrected code for your function that worked for me. You were not setting the named range for which I used the method setNamedRange and gave it a name. That and changing the variable name to which you were getting the range values to TestRange. Also, getValue() would only get you one value whereas you needed a range of values hence, used getValues() instead. But the rest of the code was fine and worked perfectly.

function saveAsSpreadsheet(){ 
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange('Sheet1!A1:B3');
  sheet.setNamedRange('buildingNameAddress', range);
  var TestRange = sheet.getRangeByName('buildingNameAddress').getValues(); 
  Logger.log(TestRange); 
  var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxxx"); 
  DriveApp.getFileById(sheet.getId()).makeCopy("Test File", destFolder); 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...