问题
I would like to clone/copy a google sheet and locate it in a drive, The script i have at the moment is working for this element but the contents appear blank becuase of formulas/importranges
Please can you help with this. Current script is
function cloneGoogleSheet2() {
const destFolder = DriveApp.getFolderById("xxxxxxxxxxx");
const file = DriveApp.getFileById("xxxxxxxxxxxxxxx").makeCopy("xxxxxxxxx", destFolder);
const ss = SpreadsheetApp.openById(file.getId());
const sheets = ss.getSheets();
sheets.forEach(sh=>{
let rng = sh.getDataRange();
rng.copyTo(rng, {contentsOnly:true});
SpreadsheetApp.flush();
});
}
Reference to similar question below
Copy a spreadsheet file to Google Drive and replace all the formulas with values
回答1:
Explanation:
Unfortunately:
importranges
can not be allowed programmatically. So you need to set get the values from the source spreadsheet and paste them to the newly created (target) spreadsheet.copyTo
can not be used between two different spreadsheets, so you can usegetValues
andsetValues
instead.The logic is to iterate over the source sheets and for every sheet get values and copy them to the corresponding target sheets.
Solution:
function cloneGoogleSheet2() {
const destFolder = DriveApp.getFolderById("folder_id");
const source_id = "spreadsheet_id_to_copy";
const source_ss = SpreadsheetApp.openById(source_id);
const file = DriveApp.getFileById(source_id).makeCopy("new_file", destFolder);
const target_ss = SpreadsheetApp.openById(file.getId());
const source_sheets = source_ss.getSheets();
const target_sheets = source_ss.getSheets();
source_sheets.forEach((sh,i)=>{
let values = sh.getDataRange().getValues();
target_sheets[i].getDataRange().setValues(values);
SpreadsheetApp.flush();
})
}
来源:https://stackoverflow.com/questions/66067520/clone-googlsheet-which-has-formulas-importranges