在 Google 电子表格中移动列

ssu*_*ndr 5 javascript google-sheets google-apps-script

现在我觉得我在这个网站上问了太多问题:),但似乎没有人问过这个问题。如果他们这样做了,请链接我。

我只想将特定列移动到同一张纸中的另一个位置(另一列之前或之后)。我看到了隐藏、插入、删除等选项。但我没有看到像移动这样基本的东西。

我真的必须获取列数据的范围,然后复制它,删除列,在我想要的位置插入列,获取范围,然后粘贴数据..?

例子:

Col A  B  C  D  E  F  G  H
    1  2  3  4  5  6  7  8
    9  10 11 12 13 14 15 16
Run Code Online (Sandbox Code Playgroud)

将 B 列移至 G 之前说:

Col A  B  C  D  E  F  G  H
    1  3  4  5  6  2  7  8
    9  11 12 13 14 10 15 16
Run Code Online (Sandbox Code Playgroud)

Mog*_*dad 3

这是一种比使用 SpreadsheetApp 方法快得多的方法。您可以一次复制整个工作表,在内存中进行修改,然后将修改后的数据写回,而不是进行复制/删除/插入/粘贴操作。

我们从一个moveColumn()与 ssurendr 的答案具有相同签名的函数开始。然而,它的工作只是读取电子表格数据,将其传递给通用 JavaScript 函数进行操作,然后将结果写回到工作表中。

/**
 * Move column in current spreadsheet
 *
 * @param {int}   iniCol  Source column index (1-based)
 * @param {int}   finCol    Destination column index (1-based)
 */
function moveColumn(iniCol, finCol) {
  var dataRange = SpreadsheetApp.getActiveSheet().getDataRange();
  var data = arrayMoveColumn( dataRange.getValues(), iniCol - 1, finCol - 1 );
  dataRange.setValues(data);
}
Run Code Online (Sandbox Code Playgroud)

下一个函数arrayMoveColumn()不是 Google 电子表格特有的。它将移动任何二维数组中的一列。Javascript 数组从 开始索引0,而电子表格方法使用1-based索引。我们添加了一些基本的错误检查,尽管它并不是万无一失的。

该函数中的主力是Array.splice()方法,该方法用于删除和插入数组中的元素。

/**
 * Move content of a "column" in a 2-d Array.
 *
 * @param {array}  data  Two-dimensional matrix (array with no null values)
 *                       Array content is changed by this function.
 * @param {int}    from  Source column index (0-based)
 * @param {int}    to    Destination column index (0-based)
 *
 * @return {array}       Resulting array (for chaining)
 */
function arrayMoveColumn( data, from, to ) {
  // Parameter error checking
  if ( !( data instanceof Array && data[0] instanceof Array ) ) throw new TypeError( 'need 2d array' );
  if ( from >= data[0].length || to >= data[0].length ) throw new Error( 'index out of bounds' );

  for (var row=0; row<data.length; row++) {
    var temp = data[row].splice(from, 1);  // take 'from'
    data[row].splice(to, 0, temp[0]);      // put  'to'
  }
  return data;
}
Run Code Online (Sandbox Code Playgroud)