繁体   English   中英

将特定的列从Excel导出到.csv Powershell

[英]Export specific columns from Excel to .csv Powershell

我有这样的代码将两个工作表的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

}

这样的事情应该起作用:

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

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM