按名称打开Goog​​le文档电子表格

时间:2013-01-08 18:03:45

标签: google-apps-script google-apps google-spreadsheet-api

我的情况是脚本正在获取输入数据并将其发送到电子表格。过了一会儿,这个电子表格变得太大了。

现在我们必须手动将项目从主电子表格移动到新的电子表格。原因是并非每个人都熟悉代码并且愿意更改代码中的ID。

我想知道是否有办法按名称打开电子表格。如果没有,是否有更好的方法来实现我们需要的东西(如上所述)

2 个答案:

答案 0 :(得分:4)

更新:DocsList现已sunset。请改用DriveApp.getFilesByName(name)


David提供了一些很好的代码来改变您的数据。如果您真正需要的只是按名称打开电子表格,那么这将解决问题:

function getSpreadsheetByName(filename) {
  var files = DocsList.find(filename);

  for(var i in files)
  {
    if(files[i].getName() == filename)
    {
      // open - undocumented function
      return SpreadsheetApp.open(files[i]);
      // openById - documented but more verbose
      // return SpreadsheetApp.openById(files[i].getId());
    }
  }
  return null;
}

答案 1 :(得分:1)

我做类似于你所要求的事情的方式是首先让脚本制作我的电子表格(我称之为冻结备份)的副本,这个副本太大了。一旦我安全地获得了副本,我就会使用相同的脚本从不再需要的太大的电子表格中删除所有这些行。 (我相信有多个冻结备份不会花费任何谷歌帐户,所以这是可行的)

请注意,我逐个删除行;这需要时间。我这样做是因为我没有删除点下面的所有行,而只删除了符合条件的某些行。

在我的情况下,除了上面的内容之外我还有另一个小程序,就是让脚本将我要删除的所有行复制到第三个电子表格中(除了冻结备份),但这似乎更多是你要求的。

这是我的代码(请注意,主要电子表格,在我们要删除行的工作表中,名为'Original',每行有A列作为时间戳;单元格A1称为时间戳):< / p>

 function ssCopy() {
  var id = "0ArVhODIsJ2....  spreadsheet key of the master spreadsheet";            
  var smsSS = SpreadsheetApp.openById(id);  


  var recordingSS = SpreadsheetApp.openById("0AvhOXv5OGF.... spreadsheet key of archive spreadsheet");//  you probably wont be using this

  var recordingSMSCopiesSheet = recordingSS.getSheets()[0];


  var outgoingSMSsheet = smsSS.getSheetByName("Original"); 
  outgoingSMSsheet.getRange("A1").setValue("Time Stamp");

  var startRow = 2;
  var numRows = outgoingSMSsheet.getDataRange().getLastRow();
  var numCols = 13;
  var dataRange = outgoingSMSsheet.getRange(startRow, 1, numRows, numCols);
  var objects = getRowsData(outgoingSMSsheet, dataRange); // Create one JavaScript object per row of data.


  var rowDataNumberArray = [];
  var rowToDeleteIndex = [];
  for (var i = 0; i < objects.length; ++i) { // Get a row object
    var rowData = objects[i];
    if(  Date.parse(rowData.timeStamp)  > Date.parse(ScriptProperties.getProperty('lastDate'))  && (rowData.done == 1) ){  //these are not used if these same 2 lines are inserted instead of here, downbelow
      var rowStuff = []
      rowToDeleteIndex.push(i);
      for(n in objects[i]){
        rowStuff.push(  objects[i][n]  )}
      rowDataNumberArray.push( rowStuff )};
    Logger.log("rowData.number1 = " + rowStuff);

  }

  Logger.log(" rowDataNumberArray ~ " + rowDataNumberArray);

  if(rowDataNumberArray.length > 0)
  {
     for(row in rowDataNumberArray)
    {recordingSMSCopiesSheet.appendRow(rowDataNumberArray[row]);}


  }

  spreadsheetFrozenBackup(id)


  for( var i = rowToDeleteIndex.length-1; i >= 0; i-- ) //backwards on purpose
  outgoingSMSsheet.deleteRow(rowToDeleteIndex[i]+ 0 + startRow); //so we don't have to re-calculate our row indexes (thanks to H. Abreu)

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



function spreadsheetFrozenBackup(id) {

  // Get current spreadsheet.
  var ss = SpreadsheetApp.openById(id);                    

  // Name the backup spreadsheet with date.
  var bssName = " Frozen Spreadsheet at: " + Utilities.formatDate(new Date(), "GMT+1:00", "yyyy-MM-dd'T'HH:mm:ss") + " : " + ss.getName() ;
  var bs = SpreadsheetApp.openById((DocsList.copy(DocsList.getFileById(ss.getId()), bssName)).getId());


}

//////////////////////////////////////////////////////////////////////////////////////////
//
// The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
// tutorial.
//
//////////////////////////////////////////////////////////////////////////////////////////

// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
//   - sheet: the sheet object that contains the data to be processed
//   - range: the exact range of cells where the data is stored
//   - columnHeadersRowIndex: specifies the row number where the column names are stored.
//       This argument is optional and it defaults to the row immediately above range; 
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
  columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
  var numColumns = range.getEndColumn() - range.getColumn() + 1;
  var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
  var headers = headersRange.getValues()[0];
  return getObjects(range.getValues(), normalizeHeaders(headers));
}

// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
//   - data: JavaScript 2d array
//   - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
  var objects = [];
  for (var i = 0; i < data.length; ++i) {
    var object = {};
    var hasData = false;
    for (var j = 0; j < data[i].length; ++j) {
      var cellData = data[i][j];
      if (isCellEmpty(cellData)) {
        continue;
      }
      object[keys[j]] = cellData;
      hasData = true;
    }
    if (hasData) {
      objects.push(object);
    }
  }
  return objects;
}

// Returns an Array of normalized Strings.
// Arguments:
//   - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    var key = normalizeHeader(headers[i]);
    if (key.length > 0) {
      keys.push(key);
    }
  }
  return keys;
}

// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
//   - header: string to normalize
// Examples:
//   "First Name" -> "firstName"
//   "Market Cap (millions) -> "marketCapMillions
//   "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
  var key = "";
  var upperCase = false;
  for (var i = 0; i < header.length; ++i) {
    var letter = header[i];
    if (letter == " " && key.length > 0) {
      upperCase = true;
      continue;
    }
    if (!isAlnum(letter)) {
      continue;
    }
    if (key.length == 0 && isDigit(letter)) {
      continue; // first character must be a letter
    }
    if (upperCase) {
      upperCase = false;
      key += letter.toUpperCase();
    } else {
      key += letter.toLowerCase();
    }
  }
  return key;
}

// Returns true if the cell where cellData was read from is empty.
// Arguments:
//   - cellData: string
function isCellEmpty(cellData) {
  return typeof(cellData) == "string" && cellData == "";
}

// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
  return char >= 'A' && char <= 'Z' ||
    char >= 'a' && char <= 'z' ||
    isDigit(char);
}

// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
  return char >= '0' && char <= '9';
}




// setRowsData fills in one row of data per object defined in the objects Array. // https://developers.google.com/apps-script/storing_data_spreadsheets
// For every Column, it checks if data objects define a value for it.
// Arguments:
//   - sheet: the Sheet Object where the data will be written
//   - objects: an Array of Objects, each of which contains data for a row
//   - optHeadersRange: a Range of cells where the column headers are defined. This
//     defaults to the entire first row in sheet.
//   - optFirstDataRowIndex: index of the first row where data should be written. This
//     defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
  var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
  var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
  var headers = normalizeHeaders(headersRange.getValues()[0]);

  var data = [];
  for (var i = 0; i < objects.length; ++i) {
    var values = []
    for (j = 0; j < headers.length; ++j) {
      var header = headers[j];
      values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
    }
    data.push(values);
  }

  var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
                                        objects.length, headers.length);
  destinationRange.setValues(data);
}