问题
I am having an issue getting my data from s = ss.getSheetByName('Last Seven Days'); to append to the top of ts = tss.getSheetByName('History');. My xp in this area is very low so may need a bit of hand-holding while I get my head around it.
Currently I can only get my function saveToHistory to append the data from 'Last Seven Days' to the bottom of the 'History Sheet' with the below script:
function saveToHistory() {
var ss, s, r, v, target,ts,tss;
ss = SpreadsheetApp.getActive();
s = ss.getSheetByName('Last Seven Days');
if (s.getRange(2, 1).getValue()) {
tss = SpreadsheetApp.getActive();
ts = tss.getSheetByName('History'); // destination Sheet tab name
s.getRange("A2:W").moveTo(ts.getRange(ts.getLastRow()+1, 1)); // Added
}
}
Is there a .getFirstRow ?? or something that would have that effect?
Thanks in advance!
回答1:
You can do this in the following way:
- Get the data from last 7 days
var lastSevenDays = sheet1.getValues(); - Get the data from the history sheet
var history = sheet2.getValues(); - Clear the history sheet
sheet2.clear(); - Concatenate the data form the history sheet to the last 7 days
lastSevenDays.concat(history); - Write the combined data back to the sheet.
sheet2.setValues(lastSevenDays);
Your final code would look like this:
(Assuming you have header on both tables and the width of the data is the same)
function moveToHistory() {
var ss = SpreadsheetApp.getActive();
var lastSevenDays = ss.getSheetByName("Last Seven Days");
var history = ss.getSheetByName("History");
var historyDataWithoutHeader = history.getDataRange().getValues();
historyDataWithoutHeader.shift(); //This removes the first row (the header)
var finalData = lastSevenDays.getDataRange().getValues().concat(historyDataWithoutHeader);
history.getRange(1, 1, finalData.length, finalData[0].length).setValues(finalData);
}
Hope this helps!
来源:https://stackoverflow.com/questions/58391433/how-to-move-data-from-sheet-1-to-sheet-2-and-append-sheet-1-data-above-old-sheet