【问题标题】:Convert excel into CSV and save将excel转成CSV并保存
【发布时间】:2019-02-11 08:52:06
【问题描述】:

我正在尝试将 xls 文件转换为 csv 文件并尝试使用 powershell 命令保存它,但出现错误:

"'$excelApp' 未被识别为内部或外部命令, 可运行的程序或批处理文件。 '$excelApp.DisplayAlerts' 未被识别为内部或外部命令, 可运行的程序或批处理文件。 '$workbook' 未被识别为内部或外部命令, 可运行的程序或批处理文件。 '$csvFilePath' 未被识别为内部或外部命令, 可运行的程序或批处理文件。 '$workbook.SaveAs' 未被识别为内部或外部命令, 可运行的程序或批处理文件。 '$workbook.Close' 未被识别为内部或外部命令, 可运行的程序或批处理文件。”

【问题讨论】:

  • 这是我试过的代码
  • set dir_Home=D:\592737\NRT\R2F\1903 for %%F in ("%dir_Home%*.xlsx") do (@echo In for loop $excelApp = New-Object - ComObject Excel.Application $excelApp.DisplayAlerts = $false $workbook = $excelApp.Workbooks.Open(%%F.FullName) $csvFilePath = %%F.FullName -replace "\.xlsx$", ".csv" $workbook .SaveAs($csvFilePath, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV) $workbook.Close() ) 暂停
  • 代码在 cmets 中不起作用,因为它被混合成一行,而是 edit 您的问题并将其包含在其中(格式正确!)
  • 您是否在 powershell 控制台中运行它?在我看来,它就像一个 .bat 文件。

标签: powershell


【解决方案1】:

试试这个代码 -

###################################################################################
### The following is a function to convert XLSX format to CSV Format
### To execute the script --> Get-ExcelData -path "Path of the XLSX sheet"
###################################################################################

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
}

执行脚本 -

Get-ExcelData -path \\PathToYourExcelSheet\ExcelSheet.xlsx

以上代码一次将 xlsx 转换为 csv。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2021-11-21
    相关资源
    最近更新 更多