繁体   English   中英

Powershell批量导出/转换Excel到TXT(unicode)

[英]Powershell batch export/convert Excel to TXT (unicode)

目标是将目录(包含子文件夹)中的所有xls文件转换为txt(unicode),将txt保存在与原始xls文件同名的相同位置。 我喜欢这样,不工作:

$files = Get-ChildItem D:\test\*.xls -recurse
Write "Loading Files..."

$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Excel.DisplayAlerts = $false

ForEach ($file in $files)
{
     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $NewFilepath = $file.Fullname -replace ".{4}$"
     $NewFilepath =  $NewFilepath + ".txt"
     $Workbook.SaveAs($NewFilepath,42)   
}
  Stop-Process -processname EXCEL
  $Excel.Quit()

它给出了例外:

No access to 'FileName.txt'.
At line:13 char:6
+      $Workbook.SaveAs($NewFilepath,42)
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

我认为这与您在退出之前终止Excel进程的方式有关。 试试这种方式:

$files = Get-ChildItem D:\test\*.xls -recurse

$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Excel.DisplayAlerts = $false

ForEach ($file in $files) {
     Write "Loading File '$($file.Name)'..."
     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $NewFilePath = [System.IO.Path]::ChangeExtension($file.Fullname,".txt")
     $Workbook.SaveAs($NewFilepath, 42)   # xlUnicodeText
}

# cleanup
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkBook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

如您所见,我还使用[System.IO.Path]::ChangeExtension()方法更改了创建新文件名的方法。 如果您必须处理.xlsx文件,这将更容易。

此外,在使用后总是释放ComObjects (底部的四行将处理它)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM