首页 > 解决方案 > 将 Excel 工作表转换为 txt 的 Powershell 脚本

问题描述

我有一个包含多个工作表的 Excel 文件,我需要使用 Powershell 将一个特定的工作表转换为 txt 文件。我“借用”了一个进行转换的脚本,但它没有指定哪个表,所以它只做第一个。

$FolderLoc = "D:\Information Services\Data\"
$files = Get-ChildItem $FolderLoc\*.xlsx -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()

我需要转换的特定工作表称为“所有详细信息”。我做了各种尝试插入一行来识别工作表,但都没有奏效。

$FolderLoc = "D:\Information Services\Data"
$files = Get-ChildItem $FolderLoc\*.xlsx -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)
     **$worksheet = "All Detail"**
     $NewFilePath = [System.IO.Path]::ChangeExtension($file.Fullname,".txt")
     $Workbook.SaveAs($NewFilepath, 42)   # xlUnicodeText
}

# cleanup
$Excel.Quit()

标签: excelpowershell

解决方案


推荐阅读