Clone Googlsheet which has formulas/importranges

不问归期 提交于 2021-02-11 06:51:52

问题


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 use getValues and setValues 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!