使用 excel office 脚本将多个 table 中的特定列合并为一个 table

Combine Specific columns from several tables using excel office script to one table

正在寻找一种从多个 table 中按名称获取特定列的方法。我的数据来自多个 sheet,列数不同,最多 38 列,因此我无法使用 getColumnById。我只需要 7 列。

首先将所有 sheet 范围转换为 table,然后获取所有 table。 我想要的是按名称获取特定列,然后在新的 sheet.

上将所有列合并为一个 table

我按照 Docs 中的示例进行了操作,但仍然无法获取每个 Table 的列名称。

我知道我的 header 值,如下例所示

function main(workbook: ExcelScript.Workbook) {
    let sheets = workbook.getWorksheets();
    for (let sheet of sheets) {
        sheet.getTables()[0].convertToRange();
        sheet.addTable(sheet.getRange('A1').getUsedRange().getAddress(),true)
    }
    workbook.getWorksheet('Combined')?.delete();
    const newSheet = workbook.addWorksheet('Combined');
    const tables = workbook.getTables();
    const headerValues = [['Column1', 'Column6', 'Column8', 'Column9','Column11', 'Column16', 'Column18', 'Column19']];
    const targetRange = newSheet.getRange('A1').getResizedRange(headerValues.length - 1, headerValues[0].length - 1);
    targetRange.setValues(headerValues);
    const combinedTable = newSheet.addTable(targetRange.getAddress(), true);
    for (let table of tables) {
        let dataValues = table.getColumnByName( // this where am stuck //).getRangeBetweenHeaderAndTotal().getTexts();
        let rowCount = table.getRowCount();

        // If the table is not empty, add its rows to the combined table.
        if (rowCount > 0) {
            combinedTable.addRows(-1, dataValues);
        }
    }

}

感谢您的帮助。 乔治

几件事:

  1. 在这种情况的大多数情况下,我建议迭代 通过一组特定的 table 个对象。不幸的是,那是 在这里很难做到。每次取消链接并重新创建新的 table, Excel 可能会给您的 table 一个新名字。这使得很难 与 table 一起工作。您可以通过以下方式在代码中解决此问题 在取消链接之前捕获 table 名称,取消链接 table, 重新创建 table,并将 table 名称设置为原始名称 捕获。如果你走那条路,那么你可以可靠地使用 table 个名字
  2. 因为 table 这种情况下的名字可能有点棘手,我要 使用 sheet 名称,以便我可以使用包含的 sheets 底层 tables。这将允许我们使用和获取数据 tables 无论它们在 sheets 中的名称如何。

请看下面我的代码:

function main(workbook: ExcelScript.Workbook) {

//JSON object called SheetAndColumnNames. On the left hand side is the sheet name. 
 //On the right hand side is an array with the column names for the table in the sheet.

  //NOTE: replace the sheet and column names with your own values

  let columnNames : string[] = ["ColA","ColB","ColC"]
  const sheetAndColumnNames = {
    "Sheet1": columnNames,
    "Sheet2": columnNames
  }

//JSON object called columnNamesAndCellValues. On the left hand side is the column name. 
 //On the right hand side is an array that will hold the values for the column in the table.

//NOTE: replace these column names with your own values
  const columnNamesAndCellValues = {
    "ColA": [],
    "ColB": [],
    "ColC": []
  }


//Iterate through the sheetAndColumnNames object
  for (let sheetName in sheetAndColumnNames) {

//Use sheet name from JSON object to get sheet
      let sheet: ExcelScript.Worksheet = workbook.getWorksheet(sheetName)

//get table from the previously assigned sheet
      let table: ExcelScript.Table = sheet.getTables()[0]

//get array of column names to be iterated on the sheet
      let tableColumnNames: string[] = sheetAndColumnNames[sheetName]

//Iterate the array of table column names
      tableColumnNames.forEach(columnName=> {

//get the dataBodyRange of the tableColumn
        let tableColumn : ExcelScript.Range = table.getColumn(columnName).getRangeBetweenHeaderAndTotal()

//iterate through all of the values in the table column and add them to the columnNamesAndCellValues array for that column name
        tableColumn.getValues().forEach(value=>{
          columnNamesAndCellValues[columnName].push(value)
        })
      })
  }

  //Delete previous worksheet named Combined
  workbook.getWorksheet("Combined")?.delete()

  //Add new worksheet named Combined and assign to combinedSheet variable
  let combinedSheet : ExcelScript.Worksheet = workbook.addWorksheet("Combined")

  //Activate the combined sheet
  combinedSheet.activate()

//get the header range for the table
  let headerRange : ExcelScript.Range = combinedSheet.getRangeByIndexes(0,0,1,columnNames.length)

//set the header range to the column headers
  headerRange.setValues([columnNames])

  //iterate through the arrays returned by the columnNamesAndCellValues object to write to the Combined sheet
  columnNames.forEach((column,index)=>{
    combinedSheet.getRangeByIndexes(1, index, columnNamesAndCellValues[column].length, 1).setValues(columnNamesAndCellValues[column])
    })

  //Get the address for the current region of the data written from the tableColumnData array to the sheet
  let combinedTableAddress : string = combinedSheet.getRange("A1").getSurroundingRegion().getAddress()

  //Add the table to the sheet using the address and setting the hasHeaders boolean value to true
  combinedSheet.addTable(combinedTableAddress,true)
}