简体   繁体   中英

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. 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. 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. This will make it easier if at one point you have to deal with .xlsx files.

Also, always release ComObjects after use (the four lines at the bottom will take care of that)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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