我在Powershell中创建了以下函数,将.xlsx文件转换为.csv,该脚本在windows server 2012机器上运行。脚本完成没有任何错误,但没有进行转换。当我有相同的脚本时尝试在win 10机器上运行完美。可以请你确认如何解决这个问题。是不是因为服务器操作系统没有安装excel?
function xlsx_to_csv($xlinput,$csvout) {
$excel = New-Object -ComObject excel.application
$excel.DisplayAlerts = $false
$Workbook = $excel.Workbooks.Open("$xlinput")
$Workbook.SaveAs("$csvout",6)
$excel.Quit()
}
xlsx_to_csv $yest_xl_in $yest_csv_in
$ yest_xl_in和$ yest_csv_in是xlsx和csv文件位置。
答案 0 :(得分:0)
这是将XLSX
文件转换为csv
的更优雅的功能。我已经使用它已经有一段时间了,它从来没有让我失望过! :)
function Get-ExcelData {
[CmdletBinding(DefaultParameterSetName='Worksheet')]
Param(
[Parameter(Mandatory=$true, Position=0)]
[String] $Path,
[Parameter(Position=1, ParameterSetName='Worksheet')]
[String] $WorksheetName = 'Sheet1',
[Parameter(Position=1, ParameterSetName='Query')]
[String] $Query = 'SELECT * FROM [Sheet1$]'
)
switch ($pscmdlet.ParameterSetName) {
'Worksheet' {
$Query = 'SELECT * FROM [{0}$]' -f $WorksheetName
break
}
'Query' {
# Make sure the query is in the correct syntax (e.g. 'SELECT * FROM [SheetName$]')
$Pattern = '.*from\b\s*(?<Table>\w+).*'
if($Query -match $Pattern) {
$Query = $Query -replace $Matches.Table, ('[{0}$]' -f $Matches.Table)
}
}
}
# Create the scriptblock to run in a job
$JobCode = {
Param($Path, $Query)
# Check if the file is XLS or XLSX
if ((Get-Item -Path $Path).Extension -eq 'xls') {
$Provider = 'Microsoft.Jet.OLEDB.4.0'
$ExtendedProperties = 'Excel 8.0;HDR=YES;IMEX=1'
} else {
$Provider = 'Microsoft.ACE.OLEDB.12.0'
$ExtendedProperties = 'Excel 12.0;HDR=YES'
}
# Build the connection string and connection object
$ConnectionString = 'Provider={0};Data Source={1};Extended Properties="{2}"' -f $Provider, $Path, $ExtendedProperties
$Connection = New-Object System.Data.OleDb.OleDbConnection $ConnectionString
try {
# Open the connection to the file, and fill the datatable
$Connection.Open()
$Adapter = New-Object -TypeName System.Data.OleDb.OleDbDataAdapter $Query, $Connection
$DataTable = New-Object System.Data.DataTable
$Adapter.Fill($DataTable) | Out-Null
}
catch {
# something went wrong ??
Write-Error $_.Exception.Message
}
finally {
# Close the connection
if ($Connection.State -eq 'Open') {
$Connection.Close()
}
}
# Return the results as an array
return ,$DataTable
}
# Run the code in a 32bit job, since the provider is 32bit only
$job = Start-Job $JobCode -RunAs32 -ArgumentList $Path, $Query
$job | Wait-Job | Receive-Job
Remove-Job $job
}
现在要获取csv
文件,您只需执行 -
$csvfile = Get-ExcelData -Path 'PathToYourExcelFile\YourExcelFile.xlsx'
$csvfile | Export-Csv -path $env:USERPROFILE\Desktop\CsvFileName.csv -NoTypeInformation #Save the csv file on your Desktop