【问题标题】:Copy multiple Excel worksheets from multiple workbooks to a new workbook using PowerShell使用 PowerShell 将多个 Excel 工作表从多个工作簿复制到新工作簿
【发布时间】:2017-11-01 00:03:32
【问题描述】:

我在这方面已经有一段时间了,但似乎找不到任何能完全满足我要求的东西。我正在处理这篇文章: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 文件,而不是覆盖现有的目标文件,但我想我可以弄清楚这部分。

【问题讨论】:

    标签: excel powershell


    【解决方案1】:

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

    【讨论】:

    • 感谢 Ashleedawg。我以前没有在 PowerShell 中使用过参数,但是感谢 Krisz 的示例,我了解了它们是如何工作的。如果我使用参数,我是否还需要指定我要查找的文件名?
    【解决方案2】:

    此功能会将工作表从一个 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"
    

    【讨论】:

    • 谢谢克里斯。我真的很感激帮助。我面临的问题是我不想命名所有文件,因为文件名会不断变化。此外,我不确定如何使它工作以创建一个新文件,而不是保存在目标文件上。我尝试使用 $xl.Workbooks.Add,但我不断收到有关 COMException 的错误。
    • PowerShell 为您提供了很多构建文件列表的选项,一旦您拥有文件列表,您就可以将其通过管道传输到此函数...例如:ls .xlsx -recursive | where-object name -like *MyExcelFile
    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2013-03-11
    • 1970-01-01
    相关资源
    最近更新 更多