Резервное копирование только значений или преобразование формул в значения после резервного - PullRequest
0 голосов
/ 02 апреля 2020

Итак, я пытаюсь сделать резервную копию электронной таблицы Google с помощью скрипта приложений, потому что каждый месяц данные будут меняться, и я хочу записать, какие данные были в прошлом. Я могу просто сделать копию таблицы.

function makeCopy() {

// generates the timestamp and stores in variable formattedDate as year-month-date hour-minute-second
var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd' 'HH:mm:ss");

// gets the name of the original file and appends the word "copy" followed by the timestamp stored in formattedDate
var name = SpreadsheetApp.getActiveSpreadsheet().getName() + formattedDate;

// gets the destination folder by their ID. REPLACE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx with your folder's ID that you can get by opening the folder in Google Drive and checking the URL in the browser's address bar
var destination = DriveApp.getFolderById("I know this is supposed to be the folderID");

// gets the current Google Sheet file
var file = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId())

// makes copy of "file" with "name" at the "destination"
file.makeCopy(name, destination);


}

Но данные в таблице будут меняться в зависимости от формул в течение дня или около того после того, как я закончу за месяц. Я только хочу скопировать значения. Я почесал голову об этом в течение нескольких часов, и мне было интересно, есть ли у кого-нибудь мысли? Я не особенно хорош в кодировании, поэтому он должен быть достаточно приличным c ответами.

Одна мысль, которая у меня была, - сделать копии всех листов в электронной таблице, преобразовать их в значения скопировать эти листы в новую электронную таблицу, а затем удалить эти копии в оригинале? Это было бы немного утомительно, но сейчас есть только 4 вкладки. "Форма" "BankRecords" "Операции" и "GLAccounts"

Ответы [ 2 ]

1 голос
/ 02 апреля 2020
  • Для скопированной электронной таблицы вы хотите преобразовать значения, заданные формулами, в значения только без формул.
  • Вы хотите добиться этого, изменив скрипт Google Apps.

Если мое понимание верно, как насчет этого ответа? Пожалуйста, подумайте об этом как об одном из нескольких возможных ответов.

Точка модификации:

  • В этом случае я хотел бы предложить преобразовать вышеуказанную ситуацию, используя copyTo, в скопированную Электронная таблица.

Модифицированный скрипт:

Если ваш скрипт модифицирован как простая модификация, пожалуйста, измените его следующим образом.

С:
file.makeCopy(name, destination);
Кому:
const copiedSpreadsheet = file.makeCopy(name, destination);
SpreadsheetApp.open(copiedSpreadsheet).getSheets().forEach(r => {
  const range = r.getDataRange();
  range.copyTo(range, {contentsOnly: true});
});

Примечание:

  • Пожалуйста, включите V8 в редакторе сценариев.

Ссылка:

Если я неправильно понял ваш вопрос, а это не то направление, в котором вы хотите, прошу прощения.

0 голосов
/ 02 апреля 2020

Итак, я сделал уродливый обходной путь. Если кто-то хочет рассказать мне, как его почистить, это было бы здорово, но если нет, то это по крайней мере функционально Мое исправление: я сделал промежуточный резервный лист, которому были предоставлены все разрешения на импорт для каждого из необходимых листов. Затем я создал функцию, основанную на этом: https://www.labnol.org/code/20239-copy-google-spreadsheets для каждой вкладки, для которой нужно создать резервную копию. (К сожалению, много дублирования, и если я захочу добавить еще несколько вкладок, это будет боль в шее.) Затем, после всех этих функций, я добавил обратно в оригинальную функцию makecopy, настроенную так, чтобы она будет копировать на основе промежуточной резервной копии. Вот код:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Custom Scripts')
      .addItem('Backup', 'cloneGoogleSheet')
      .addToUi();
}

function cloneGoogleSheet() {
cloneMain()
cloneCR()
cloneGS()
cloneJD()
cloneJS()
cloneJW()
cloneKS()
cloneSS()
cloneTR()
cloneWJ()
cloneWK()
makeCopy()
}

function cloneMain(Main, Main1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('Main');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('Main1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneCR(CR, CR1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('CR');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('CR1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneGS(GS, GS1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('GS');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('GS1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneJD(JD, JD1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('JD');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('JD1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneJS(JS, JS1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('JS');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('JS1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneJW(JW, JW1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('JW');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('JW1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneKS(KS, KS1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('KS');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('KS1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneSS(SS, SS1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('SS');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('SS1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneTR(TR, TR1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('TR');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('TR1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneWJ(WJ, WJ1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('WJ');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('WJ1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function cloneWK(WK, WK1) {

  // source doc
  var sss = SpreadsheetApp.openById('1VM1Pf4PQyP2V_oNDcTHADdqQ-9hY8vALHuEnuIhOKG4');

  // source sheet
  var ss = sss.getSheetByName('WK');

  // Get full range of data
  var SRange = ss.getDataRange();

  // get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();

  // get the data values in range
  var SData = SRange.getValues();

  // target spreadsheet
  var tss = SpreadsheetApp.openById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE');

  // target sheet
  var ts = tss.getSheetByName('WK1');

  // Clear the Google Sheet before copy
  ts.clear({contentsOnly: true});

  // set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

};

function makeCopy() {

// generates the timestamp and stores in variable formattedDate as year-month-date hour-minute-second
var formattedDate = Utilities.formatDate(new Date(), "EST5EDT", "yyyyMMdd' 'HH:mm");

// gets the name of the original file and appends the word "copy" followed by the timestamp stored in formattedDate
var name = "Master Sheet - " + formattedDate;

// gets the destination folder by their ID. REPLACE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx with your folder's ID that you can get by opening the folder in Google Drive and checking the URL in the browser's address bar
var destination = DriveApp.getFolderById("1E5EodsDaaT6a8wkRZ-NtmszzV9DTgQok");

// gets the intermediary backup
var file = DriveApp.getFileById('1NP7GNjnGHpkRcm7nG_-_Of8f--zQiG7GxO_aOY3ppXE')

// makes copy of "file" with "name" at the "destination"
file.makeCopy(name, destination);



}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...