简体   繁体   English

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

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

The goal is to convert all xls files in a directory (with subfolders) to txt (unicode), saving txt in the same locations with same names as original xls files. 目标是将目录(包含子文件夹)中的所有xls文件转换为txt(unicode),将txt保存在与原始xls文件同名的相同位置。 I have it like this, not working: 我喜欢这样,不工作:

$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()

It gives en exception: 它给出了例外:

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

I think this has to do with the way you kill the Excel process before quitting it. 我认为这与您在退出之前终止Excel进程的方式有关。 Try this way: 试试这种方式:

$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()

As you can see, I have also changed the method of creating a new filename by using the [System.IO.Path]::ChangeExtension() method. 如您所见,我还使用[System.IO.Path]::ChangeExtension()方法更改了创建新文件名的方法。 This will make it easier if at one point you have to deal with .xlsx files. 如果您必须处理.xlsx文件,这将更容易。

Also, always release ComObjects after use (the four lines at the bottom will take care of that) 此外,在使用后总是释放ComObjects (底部的四行将处理它)

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

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