【问题标题】:Powershell - add multiple columns to multiple excel filesPowershell - 将多列添加到多个 excel 文件
【发布时间】:2021-10-02 09:54:54
【问题描述】:

我有一个文件夹,其中包含 50 多个 excel 文件(以下路径中的“项目转储”。)所有这些文件都包含相同的确切数据(用于 MoM 报告的每月存档数据)我需要更新所有这些文件以添加 10 个新的列标题 - 这些列中没有任何数据,只需将它们添加到表中以匹配将在其中包含数据的最新月份提取。

我一直在使用 Powershell,并且有一个脚本可以一次将一列添加到一个文件中,但老实说,我手动打开每个文件并自己添加列会更快。我似乎无法弄清楚如何更改我的脚本来执行它对多个文件(和多个列)所做的事情,任何帮助将不胜感激!

背景;引用是我的项目转储文件夹中的特定文件。第 50 列是第一个空白列,需要添加到表中:

(Get-ChildItem "C:\Downloads\Project dump\ArchiveJAN21.xlsx")|
foreach-object {
    $xl=New-Object -ComObject Excel.Application
    $wb=$xl.workbooks.open($_)
    $ws = $wb.worksheets.Item(1)
    $ws.Columns.ListObject.ListColumns.Add(50)
    $ws.Cells.Item(1,50) ='Call Type'
    $wb.Save()
    $xl.Quit()
    while([System.Runtime.Interopservices.Marshal]::ReleaseComObject([System.__ComObject]$xl)){'released'| Out-Null}
}

【问题讨论】:

    标签: powershell anaconda


    【解决方案1】:

    您需要在循环之前定义 Excel 对象并在之后退出。
    此外,使用 Get-ChildItem 从文件夹路径获取 FileInfo 对象,而不是文件的硬编码路径。

    试试:

    # an array with the new column names
    $newColumns = 'Call Type','NewCol2','NewCol3','NewCol4','NewCol5','NewCol6','NewCol7','NewCol8','NewCol9','NewCol10'
    
    # create the Excel object outside of the loop
    $xl = New-Object -ComObject Excel.Application
    $xl.Visible = $false
    
    # loop thtrough the files in the folder
    (Get-ChildItem -Path 'C:\Downloads\Project dump' -Filter '*.xlsx' -File ) | ForEach-Object {
        $wb = $xl.WorkBooks.Open($_.FullName)
        $ws = $wb.Worksheets.Item(1)
        # get the number of columns in the sheet
        $startColumn = $ws.UsedRange.Columns.Count
        for ($i = 0; $i -lt $newColumns.Count; $i++) {
            $startColumn++  # increment the column counter
            $ws.Cells.Item(1, $startColumn) = $newColumns[$i]
        }
        $wb.Close($true)  # $true saves the changes
    }
    
    # quit Excel and clean COM objects from memory
    $xl.Quit()
    # clean up the COM objects used
    $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($ws)
    $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb)
    $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
    

    【讨论】:

    • 非常感谢!这行得通!另外,我非常感谢代码中的 cmets,它对学习逻辑非常有帮助。
    • @Sav 谢谢。是的,我总是喜欢添加内联 cmets,因为你永远不知道何时需要调整代码,它有助于提醒正在发生的事情,即使它们确实包含拼写错误;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    相关资源
    最近更新 更多