且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法让两张纸同步?

更新时间:2023-08-30 23:36:40

您可以通过在两个电子表格中添加一个脚本它是更改触发器上其他电子表格的内容。例如,如果您要将以下内容添加到这两个电子表格中,请交换源和目标信息。

  var sourceSpreadsheetID =ID HERE; 
var sourceWorksheetName =SHEET NAME HERE;
var destinationSpreadsheetID =ID HERE;
var destinationWorksheetName =SHEET NAME HERE;

函数importData(){
var thisSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
var thisWorksheet = thisSpreadsheet.getSheetByName(sourceWorksheetName);
var thisData = thisWorksheet.getDataRange();
var toSpreadsheet = SpreadsheetApp.openById(destinationSpreadsheetID);
var toWorksheet = toSpreadsheet.getSheetByName(destinationWorksheetName);
var toRange = toWorksheet.getRange(1,1,thisData.getNumRows(),thisData.getNumColumns())
toRange.setValues(thisData.getValues());

$ / code>

只需为importData函数添加更改触发器,然后进行任何更改要么将文件复制到其他电子表格,从而保持两个同步。

显然,如果两张电子表格都在同一时间更新,您将遇到麻烦。

There isn't a way to share only one sheet of one spreadsheet in Google Docs. So, you have to share an entire spreadsheet. So, I was thinking in writing a script to synchronize two sheets (each one in a different spreadsheet). I thought using a function to get rows as array to do this. Is there a better strategy to do that?

One way you could accomplish this is by adding a script to both spreadsheets that copies it's contents to the other spreadsheet on a change trigger. For example if you were to add something like the below to both spreadsheets, swapping the source and destination information around.

var sourceSpreadsheetID = "ID HERE";
var sourceWorksheetName = "SHEET NAME HERE";
var destinationSpreadsheetID = "ID HERE";
var destinationWorksheetName = "SHEET NAME HERE";

function importData() {
  var thisSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
  var thisWorksheet = thisSpreadsheet.getSheetByName(sourceWorksheetName);
  var thisData = thisWorksheet.getDataRange();
  var toSpreadsheet = SpreadsheetApp.openById(destinationSpreadsheetID);
  var toWorksheet = toSpreadsheet.getSheetByName(destinationWorksheetName);
  var toRange = toWorksheet.getRange(1, 1, thisData.getNumRows(), thisData.getNumColumns())
  toRange.setValues(thisData.getValues()); 
}

Just add a change trigger for the importData function and then when any changes are made to either document it will copy the contents to the other spreadsheet, thus keeping the both synced.

Obviously if both spreadsheets are being updated at the same time you will run into trouble.