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

mzillmmw  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(143)

一个寻找一种方法来获得特定列的名称从几个表。我的数据来自几个工作表不同数量的列多达38列,所以我不能使用getColumnById。我只需要7列从这个。
首先我把所有的工作表范围转换成表格,然后我得到所有的表格。我想要的是得到特定的列的名称和合并到一个新的工作表上的所有表格。
我遵循了文档中的示例,但在获取每个表的列名时遇到了麻烦。
我知道我的标题值,如下例所示

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);
        }
    }

}

谢谢你的帮助乔治

wgx48brx

wgx48brx1#

几件事:
1.在大多数情况下,我建议迭代一组特定的表对象。不幸的是,这在这里很难做到。每次您取消链接并重新创建一个新表时,Excel可能会给您的表一个新名称。这使得使用该表很困难。您可以在代码中通过以下方法解决此问题:在取消链接之前捕获表名称,取消链接该表,重新创建该表,并将表名设置为最初捕获的表名。如果您采用这种方法,则可以可靠地使用表名
1.因为在这个场景中,表名可能有点复杂,所以我将使用工作表名,以便可以处理包含基础表的工作表。这将允许我们使用表并从表中获取数据,而不管表在工作表中的名称是什么。
请看下面的代码:

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)
    }

相关问题