通过Powershell在Excel中查找和添加数据

时间:2017-05-24 19:08:25

标签: excel-vba powershell vba excel

我有一个CSV文件,其中包含类似的产品以及旁边的每个产品的数量。

CSV文件中的示例

Qty Ordered         Product/Item Description    Top row (header)
   7                Product1
   3                Product2
   5                Product1
   3                Product3

我需要一种方法来查找所有类似的产品#s,加上他们的数量,并将每个相似产品的总数放在一个新行中。

Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property 
@{
Multiselect = $false # Multiple files can be chosen
Filter = 'Excel (*.csv, *.xlxs)|*.csv;*.xlsx' # Specified file types
}

[void]$FileBrowser.ShowDialog()

$file = $FileBrowser.FileNames;




[Reflection.Assembly]::LoadWithPartialName
("Microsoft.Office.Interop.Excel")|Out-Null
$excel = New-Object Microsoft.Office.Interop.Excel.ApplicationClass
$excel.Visible = $true 
$wb = $excel.Workbooks.Open($file)
$ws = $wb.ActiveSheet
$c = $ws.Columns
$c.Item(2).hidden = $true

此代码要求用户选择csv文件,隐藏无用的列并自动调整重要列的大小。

1 个答案:

答案 0 :(得分:1)

您可以使用Import-CSV然后使用Group-Object,而不是将Excel用作COM对象。然后遍历各组以获取所需信息。

Add-Type -AssemblyName System.Windows.Forms 
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    Multiselect = $false # Multiple files can be chosen 
    Filter = 'Excel (.csv, *.xlxs)|.csv;*.xlsx' # Specified file types 
} 
[void]$FileBrowser.ShowDialog() 
ForEach ($file in $FileBrowser.FileNames) {
    $CSV = Import-CSV $file | Add-Member -Name Total -Value 0 -MemberType NoteProperty
    $Groups = $CSV | Group-Object "Product/Item Description"
    $NewCSV = Foreach ($Group in $Groups) {
        $Count = 0
        $Group.Group."Qty Ordered" | ForEach-Object {$Count += $_}
        Foreach ($value in $CSV) {
            If ($value."Product/Item Description" -eq $Group.Name) {
                 $value.Total = $Count
                 $value
            }
        }
    }
    Export-CSV "$filenew" -NoTypeInformation
}