【问题标题】:create csv from xls using powershell使用 powershell 从 xls 创建 csv
【发布时间】:2019-01-31 13:09:29
【问题描述】:

我想创建 powershell 脚本,它从 .xls 文件创建我的 csv 文件,但我不知道如何在没有 vba 的情况下使用 powershell。

到目前为止我有这个:

ConvertTo-Csv "C:\Users\Me\TestsShella\test.xlsx"  | Out-File Q:\test\testShella.csv

但它不起作用。

【问题讨论】:

标签: powershell


【解决方案1】:

在正在运行的机器上使用 Excel 将其用作 COM 对象:

## Q:\Test\2019\01\31\SO_54461362.ps1

$InFile = Get-Item "$($Env:USERPROFILE)\TestsShella\test.xlsx"
$OutFile= $InFile.FullName.replace($InFile.Extension,".csv")

$Excel = new-object -ComObject "Excel.Application"
$Excel.DisplayAlerts = $True
$Excel.Visible = $False # $True while testing

$WorkBook = $Excel.Workbooks.Open($InFile.FullName)
$WorkBook.SaveAs($OutFile, 6) # 6 -> type csv
$WorkBook.Close($True)

$Excel.Quit()
[void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)

根据区域设置(小数点/逗号),csv 文件将以逗号或分号分隔。


不安装Excel,使用已经推荐的模块ImportExcel

$InFile = Get-Item "$($Env:USERPROFILE)\TestsShella\test.xlsx"
$OutFile= $InFile.FullName.replace($InFile.Extension,".csv")

Import-Excel $Infile.FullName | Export-Csv $OutFile -NoTypeInformation

这会生成一个 .csv 文件,其中包含 所有 字段双引号和逗号分隔。

【讨论】:

    【解决方案2】:

    为此有一个预构建的库:

    https://www.powershellgallery.com/packages/ImportExcel/5.4.4

    然后,您将可以使用 import-excel 函数/cmdlet,并且能够导入、转换为 csv 然后导出

    【讨论】:

      【解决方案3】:

      也许这可行:

      rename-item -Path "C:\Users\Me\TestsShella\test.xlsx" -NewName "item.csv"
      

      打开CSV会有提示信息,但是CSV的格式类似于XLSX。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-22
        • 1970-01-01
        • 2015-02-02
        • 1970-01-01
        • 2011-10-27
        • 1970-01-01
        • 2017-10-22
        • 1970-01-01
        相关资源
        最近更新 更多