How to move data from Sheet 1 to Sheet 2 and append Sheet 1 data above old Sheet 2 data

时光怂恿深爱的人放手 提交于 2020-03-04 03:43:29

问题


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:

  1. Get the data from last 7 days var lastSevenDays = sheet1.getValues();
  2. Get the data from the history sheet var history = sheet2.getValues();
  3. Clear the history sheet sheet2.clear();
  4. Concatenate the data form the history sheet to the last 7 days lastSevenDays.concat(history);
  5. 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

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