.xlsm 到 csv 使用 Powershell

.xlsm to csv using Powershell

我想将文件夹中的多个文件从 .xlsm 转换为 csv。 Excel 文件包含多个工作表。 因为目前我对 Powershell 的了解非常有限,所以我在网上搜索了一个脚本并在 Extract and convert all Excel worksheets into CSV files using PowerShell

找到了一个

问题是,在某些情况下,我设法使这些脚本工作(一个脚本调用另一个),但我还没有弄清楚它何时或如何发生。 我正在 运行 从 Powershell ISE 获取脚本并收到以下错误消息:

Exception calling "Open" with "1" argument(s): "Sorry, we couldn't find C:\Docs. Is it possible it was moved, renamed or deleted?" At C:\Docs\xlstocsv.ps1:9 char:5 + $wb = $E.Workbooks.Open($excelFile) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation

因为我已经成功地 运行 这些脚本几次,所以假设脚本是正确的并且我的 Powershell(?) 设置有问题是正确的吗? 我 运行 没主意了。

PS希望可以在这里粘贴其他网页的链接

编辑 已添加代码。

脚本一个(我从Powershell ISE开始的那个):

$ens = Get-ChildItem "C:\Docs\" -filter *.xlsm
foreach($e in $ens)
{   [threading.thread]::CurrentThread.CurrentCulture = 'en-US'
    ExportWSToCSV -excelFileName $e.BaseName -csvLoc "C:\Docs\Final\"
}

脚本二:

Function ExportWSToCSV ($excelFileName, $csvLoc)

{   [threading.thread]::CurrentThread.CurrentCulture = 'en-US'
    $excelFile = "C:\Docs\"
    $E = New-Object -ComObject Excel.Application
    $E.Visible = $false
    $E.DisplayAlerts = $false
    $wb = $E.Workbooks.Open($excelFile)
    foreach ($ws in $wb.Worksheets)
    {
        $n = $excelFileName + "_" + $ws.Name
        $ws.SaveAs($csvLoc + $n + '.csv', 6)
    }
    $E.Quit()
}
ExportWSToCSV -excelFileName "file" -csvLoc "C:\Docs\Final\"     

我添加了“[threading.thread]::CurrentThread.CurrentCulture = 'en-US'”部分,我能够 运行 这些脚本成功,但只有一次。所以这基本上似乎我可以从代码中丢弃这一行。

如果您的唯一目标是将文件从 .xlsm 转换为 .csv,您可以这样完成(使用您的示例片段):

function Convert-XlsmToCsv {
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [Alias('FullName')]
        [string] $Path
    )
    begin {
        $excel = New-Object -ComObject Excel.Application -Property @{
            Visible       = $false
            DisplayAlerts = $false
        }
    }
    process {
        $root = Split-Path -Path $Path
        $filename = [System.IO.Path]::GetFileNameWithoutExtension($Path)
        $workbook = $excel.Workbooks.Open($Path)
        foreach ($worksheet in $workbook.Worksheets) {
            $name = Join-Path -Path $root -ChildPath "${filename}_$($worksheet.Name).csv"
            try {
                $worksheet.SaveAs($name, 6)
            } catch {
                Write-Error -Message "Failed to save csv! Path: '$name'. $PSItem"
            }
        }
    }
    end {
        $excel.Quit()
        $null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel)
    }
}

正在使用:

Get-ChildItem -Path C:\Docs -Filter *.xlsm |
    Convert-XlsmToCsv

这做了一些假设,但编辑起来很容易。