使用PowerShell将多个Excel工作表从多个工作簿复制到新工作簿

时间:2017-10-31 13:47:42

标签: excel powershell

我已经有一段时间了,似乎找不到任何我想要的东西。我正在处理这篇文章:How to use PowerShell to copy several Excel worksheets and make a new one但它并没有完全符合我的要求。我试图从多个工作簿中复制所有工作表并将它们放在一个新的工作簿中。理想情况下,我想从其中一个工作簿中获取文件名,并使用它将新文件命名为新目录。

我找到了许多可以执行此操作的代码示例,但是我缺少一些关键功能,并且不确定如何实现它们。以下是我现在工作的一个例子:

$file1 = 'C:\Users\Desktop\TestFolder\PredictedAttritionReport.xlsx' # source's fullpath
$file2 = 'C:\Users\Desktop\TestFolder\AdvisorReport' # destination's fullpath

$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item('Report') # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('Report') # source sheet to copy

$sh1_wb1.Name = "DeleteMe$(get-date -Format hhmmss)" #Extremely unlikely to be a duplicate name
$sheetToCopy.copy($sh1_wb1)  # copy source sheet to destination workbook
$sh1_wb1.Delete()

$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel

我遇到的问题是我需要这个才能工作,这样我就不必输入实际的文件名,因为这些名称每次创建时可能会有所不同,可能有3或4个文件使用多个工作表,此示例仅使用两个命名文件。此外,我希望能够将所有工作表复制到一个文件中,而不仅仅是一个命名的工作表,在这种情况下是“报告”。最后一块是将它保存为新的Excel文件,而不是覆盖现有的目标文件,但我想我可以把它解决掉。

2 个答案:

答案 0 :(得分:0)

您可以在调用脚本时指定参数,并根据需要使用指定的值代替工作表/文件名。阅读PowerShell Parameters here。如果您需要有关如何实施的更多信息,请回复。

答案 1 :(得分:0)

此功能将工作表从一个Excel工作簿复制到另一个工作簿。 你可以使用Copy-AllExcelSheet命令调用一个,它被加载到内存中。

见下面的示例:

Function Copy-AllExcelSheet()
{
    param($TargetXls, $sourceXls)
    $xl = new-object -c excel.application
    $xl.displayAlerts = $false

    $sourceWb = $xl.Workbooks.Open($sourceXls,$true,$false)
    $targetWB = $xl.Workbooks.Open($TargetXls)

    foreach($nextSheet in $sourceWb.Sheets)
    {

        $nextSheet.Copy($targetWB.Sheets[1])

    }
    $sourceWb.close($false)
    $targetWB.close($true)
    $xl.Quit()
}

#To call the function
Copy-AllExcelSheet "c:\Targetfile.xlsx" "c:\sourceFile.xlsx"