将多个 Excel 表格中的数据合并到单个表中

您所在的位置:网站首页 excel2个表格内容合并到一个表格 将多个 Excel 表格中的数据合并到单个表中

将多个 Excel 表格中的数据合并到单个表中

2024-07-13 10:28| 来源: 网络整理| 查看: 265

将多个 Excel 表格中的数据合并到单个表中 项目10/25/2023

此示例将多个 Excel 表中的数据合并到包含所有行的单个表中。 它假定使用的所有表具有相同的结构。

此脚本有两种变体:

第一个脚本合并了 Excel 文件中的所有表。 第 二个脚本 有选择地获取一组工作表中的表。 设置:示例 Excel 文件

此工作簿包含脚本所需的数据、对象和格式设置。

下载示例工作簿

示例代码:将多个 Excel 表中的数据合并到单个表中

将以下脚本添加到示例工作簿,并亲自尝试该示例!

function main(workbook: ExcelScript.Workbook) { // Delete the "Combined" worksheet, if it's present. workbook.getWorksheet('Combined')?.delete(); // Create a new worksheet named "Combined" for the combined table. const newSheet = workbook.addWorksheet('Combined'); // Get the header values for the first table in the workbook. // This also saves the table list before we add the new, combined table. const tables = workbook.getTables(); const headerValues = tables[0].getHeaderRowRange().getTexts(); console.log(headerValues); // Copy the headers on a new worksheet to an equal-sized range. const targetRange = newSheet.getRange('A1').getResizedRange(headerValues.length-1, headerValues[0].length-1); targetRange.setValues(headerValues); // Add the data from each table in the workbook to the new table. const combinedTable = newSheet.addTable(targetRange.getAddress(), true); for (let table of tables) { let dataValues = table.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); } } } 示例代码:将选定工作表中多个 Excel 表格中的数据合并到单个表中

tables-select-copy.xlsx 下载示例文件,并将其与以下脚本一起使用,自行试用!

function main(workbook: ExcelScript.Workbook) { // Set the worksheet names to get tables from. const sheetNames = ['Sheet1', 'Sheet2', 'Sheet3']; // Delete the "Combined" worksheet, if it's present. workbook.getWorksheet('Combined')?.delete(); // Create a new worksheet named "Combined" for the combined table. const newSheet = workbook.addWorksheet('Combined'); // Create a new table with the same headers as the other tables. const headerValues = workbook.getWorksheet(sheetNames[0]).getTables()[0].getHeaderRowRange().getTexts(); const targetRange = newSheet.getRange('A1').getResizedRange(headerValues.length-1, headerValues[0].length-1); targetRange.setValues(headerValues); const combinedTable = newSheet.addTable(targetRange.getAddress(), true); // Go through each listed worksheet and get their tables. sheetNames.forEach((sheet) => { const tables = workbook.getWorksheet(sheet).getTables(); for (let table of tables) { // Get the rows from the tables. let dataValues = table.getRangeBetweenHeaderAndTotal().getTexts(); let rowCount = table.getRowCount(); // If there's data in the table, add it to the combined table. if (rowCount > 0) { combinedTable.addRows(-1, dataValues); } } }); } 培训视频:将多个 Excel 表格中的数据合并到单个表中

观看 Sudhi Ramamurthy 在 YouTube 上演练此示例。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3