簡體   English   中英

無法通過Windows Server 2012中的Power Shell將.xlsx轉換為.csv

[英]Unable to convert .xlsx to .csv through Power shell in windows server 2012

我在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文件的位置。

這是將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM