我有这样一个代码,用于将带有两个工作表的Excel文件导出到两个csv文件中。问题是我目前正在导出整个工作表,我想从我的循环中只导出这三列。如何保存它们?它们必须按顺序排列,因为我想稍后将其导入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
}
答案 0 :(得分:1)
这样的事情应该有效:
首先,设置一个数组,用于包含我们的导出用户列表,如下所示:
$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