从Excel导出特定列到.csv Powershell

我有两个工作表导出Excel文件到两个CSV文件这样的代码。问题是,我目前正在导出整个工作表,我只想从我的循环导出这3列。如何保存它们? 它们必须是有序的,因为我想稍后将它导入AD。

Function ExportWSToCSV ($excelFileName , $csvLoc){ #Sample use in a console: ExportWSToCSV -excelFileName "Test_Peoplesoft.xls" -csvLoc "y:\Application Data\CSVFiles\" $CultureOld = [System.Threading.Thread]::CurrentThread.CurrentCulture #Original culture info $CultureUS = [System.Globalization.CultureInfo]'en-US' #US culture info $excelFile = "y:\Application Data\Test_Peoplesoft.xls" #Loc of Excel file .xls , #csvLov - Loc of output files in format .csv [System.Threading.Thread]::CurrentThread.CurrentCulture = $CultureUS $E = New-Object -ComObject Excel.Application $E.Visible = $false $E.DisplayAlerts = $false $wb = $E.Workbooks.Open($excelFile) $intRow = 2 $intRowMax =($ws.UsedRange.Rows).count $elements = $email -or $costcode -or $leader Do{ foreach($ws in $wb.sheets.item("Inactive")){ if($elements -ne $null ){ $email = $ws.Cells.Item($intRow, 4).Value() $costcode = $ws.Cells.Item($intRow, 15).Value() $leader = $ws.Cells.Item($intRow, 20).Value() }else{Write-Host "Null Value in one of the attributes"} } <# foreach($ws in $wb.sheets.item("Inactive")){ $email = $ws.Cells.Item($intRow, 4).Value() $costcode = $ws.Cells.Item($intRow, 15).Value() $leader = $ws.Cells.Item($intRow, 20).Value() } #> $user = $email + "_" + $costcode + "_" + $leader write-host $intRow " " $user $intRow++ }While ($ws.Cells.Item($intRow,1).Value() -ne $null) foreach ($ws in $wb.Worksheets) { Write-Host "Processing Worksheet: " $ws.Name $n = $csvLoc + $excelFileName + "_" + $ws.Name #Name variable - Output file loc + excel file name + worksheet name $ws.SaveAs($n + ".csv", 6) #Saving file to .csv } $E.Quit() [System.Threading.Thread]::CurrentThread.CurrentCulture = $CultureOld 

}

像这样的东西应该工作:

首先,设置一个包含我们的导出用户列表的数组,如下所示:

 $exportList = @() 

(在你开始循环行之前)

然后使用do while循环遍历工作表上的行,并添加一个用户对象来添加您的导出列表

 # Create userObj with the required properties $userObj = New-Object System.Object $userObj | Add-Member -Type NoteProperty -Name Email -Value $email $userObj | Add-Member -Type NoteProperty -Name CostCode -Value $costcode $userObj | Add-Member -Type NoteProperty -Name Leader -Value $leader # Add $userObj to our list to be exported $exportList += $userObj 

然后导出到.csv

 $exportList | Export-Csv $pathToCsvFile