如何在应用程序脚本 google sheet 中按列名 (header) 获取数据

How can I get data by column name (header) in app script google sheet

如何在应用程序脚本中按列名 (header) 获取列值。我不想使用 indexes/column 列编号。我想使用 headers 检索整列数据。 我尝试了多种方法,但无法得到适当的解决方案。 我正在为 google sheet.

使用应用程序脚本 JavaScript

这是一个可能的工作流程。

解决方案:

  • 通过getDataRange获取所有sheet值。
  • 使用 shift.
  • 提取第一行(值)
  • 使用 indexOf 获取所需 header 所在的列索引。
  • 使用 map 获取对应于该列的值。

代码示例:

function getColumnValues() {
  const sheet = SpreadsheetApp.getActiveSheet(); // Change this according to your preferences
  const header = "My header"; // Change this according to your preferences
  const values = sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn()).getValues();
  const headers = values.shift();
  const columnIndex = headers.indexOf(header);
  const columnValues = values.map(row => row[columnIndex]);
  return columnValues;
}

如果您想从 csv 文件中检索信息,请尝试

function getColumnValues() {
  var id = 'id of your csv file';
  var csv = DriveApp.getFileById(id).getBlob().getDataAsString();
  const [headers, ... rows] = Utilities.parseCsv(csv);
  console.log (rows.map(row => row[headers.indexOf('yourColumnHeader')]));
}

Array.prototype.indexOf()

Spread Operator : ...(JavaScript 中的三个点)称为传播语法或传播运算符。这允许扩展诸如数组表达式或字符串之类的可迭代对象,或者扩展对象表达式。

通过这种方式,您可以按列获得 sheet 个值。提供 header 个名称。 //通过一维数组 ['ID','Name','Date','Title','SupervisorName','SupervisorEmail'] 接受 header //使用 sheet API 按列获取值。

const target_header = ['ID', 'Name', 'Date', 'Title', 'SupervisorName', 'SupervisorEmail'];

function get_dataBycolumns(target_header) {
    const values = Sheets.Spreadsheets.Values.batchGet(
        'YOUR SHEET ID', {
            ranges: [
                "Sheet1",
                // you can specify the header range. by getting the header .
                //or just go through each columns first cell , then decide return or not.
                "Sheet1!A1:CE1"
            ],
            majorDimension: "COLUMNS"
        }
    );
    const header = values.valueRanges[1].values.flat();
    const sheet_values = values.valueRanges[0].values;
    const arr_index = [];
    for (i = 0; i < target_header.length; i++) {
        header.indexOf(target_header[i]) > -1 ? arr_index.push(header.indexOf(target_header[i])) : '';
    }
    //methods 1, go through each colms first cell
    const filtered_values = sheet_values.filter((col, index) => {
        if (target_header.indexOf(col[0]) > -1) {
            return col;
        }
    });
    //methods 2, get the header first and then ge the index of header.
    const filtered_values1 = sheet_values.filter((col, index) => {
        if (target_header.indexOf(index) > -1) {
            return col;
        }
    });
}

这是一个有效的解决方案,可以避免获取不必要的额外数据:

function getColumnData(headerName) {
  const sheet = SpreadsheetApp.getActiveSheet();
  // Get column index of headerName (starts at 1)
  const columnIndex = sheet.getRange('1:1').getValues()[0].indexOf(headerName) + 1;
  // Return only headerName data
  return sheet.getRange(2, columnIndex, sheet.getLastRow() - 1, 1).getValues();
}

如果要展平 returned 的数组,则将 return 语句更改为:

return sheet.getRange(2, columnIndex, sheet.getLastRow() - 1, 1).getValues().flat();

如果您的列不均匀(例如,A 列填充到第 10 行,B 列填充到第 7 行),那么较短的列将包含空数组项。要过滤掉这些,请将 return 语句更改为:

return sheet.getRange(2, columnIndex, sheet.getLastRow() - 1, 1).getValues().flat().filter(Boolean);