使用twapi将Excel工作表从一个工作簿复制到另一个工作簿

时间:2018-11-23 09:25:32

标签: excel tcl

我正在尝试将一个文件夹中的多个excel文件合并为一个文件,并使用以下代码将所有文件中的所有工作表复制到单个文件中,但是没有运气。有人可以帮忙吗?...

set file1 {D:\Temp\CombineExcel\Work\1240676493.xlsm}
set file2 {D:\Temp\CombineExcel\Work\1735749199.xlsm}

set xl [ ::twapi::comobj Excel.Application ];
set wb [$xl Workbooks];
set wb1 [$wb Open $file1];
set wb2 [$wb Open $file2];
set f1w1s1 [$str_fil1 WorkSheets]
set f2w2s2 [$str_fil2 WorkSheets]

1 个答案:

答案 0 :(得分:0)

假设您要复制文件 1 的工作表 1 到文件 1 中,您可以这样做:

# Open COm Excel
set excel [twapi::comobj Excel.Application]
$excel DisplayAlerts [expr 0]
set workbooks [$excel Workbooks]

set wb2 [$workbooks Open $file2] ; # Open file2
set wb1 [$workbooks Open $file1] ; # Open file1

# Second file
set ws2 [$wb2 Worksheets]
set worksheetId [$ws2 Item [expr 1]] ; # First sheet of file2
$worksheetId Activate
set range [$worksheetId Cells] ; # select all...
$range Copy

# First file
set ws1 [$wb1 Worksheets]
set lastWsId [$ws1 Item [$ws1 Count]]
set worksheetId [$ws1 -callnamedargs Add After $lastWsId]
$worksheetId Activate

$worksheetId Paste ; # Paste the result in file1 after the last sheet

$wb1 Save ; # Save file1
$excel Quit

# Destroy all objects...
foreach obj [twapi::comobj_instances] {
    $obj -destroy
}

如果要复制特定的图纸,可以使用名称[$worksheetId Name]