【发布时间】:2015-11-08 08:01:32
【问题描述】:
我正在尝试将具有多张工作表的 excel 文件拆分为多个文件,并搜索了此博客:Extract worksheets from Excel into separate files with PowerShell。我尝试了 xls 文件,它工作正常。但是当我尝试使用 xlsx 文件时,它只输出整个源文件,当我使用 Excel 应用程序打开生成的文件时,每个工作表都作为默认工作表。我为解决方案而苦苦挣扎,但没有运气。我的测试代码就像一击:
$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible = $false #Runs Excel in the background.
$Excel.DisplayAlerts = $false #Supress alert messages.
$filepath ="D:\powershell\test.xlsx"
$Workbook = $Excel.Workbooks.open($filepath)
$WorkbookName = "test.xlsx"
$output_type = "xlsx"
if ($Workbook.Worksheets.Count -gt 0) {
write-Output "Now processing: $WorkbookName"
$FileFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
$WorkbookName = $filepath -replace ".xlsx", ""
foreach($Worksheet in $Workbook.Worksheets) {
$ExtractedFileName = $WorkbookName + "~~" + $Worksheet.Name + "." + $output_type
$Worksheet.SaveAs($ExtractedFileName, $FileFormat)
write-Output "Created file: $ExtractedFileName"
}
}
$Workbook.Close()
$Excel.Quit()
【问题讨论】:
-
我不确定
if ($Workbook.Worksheets.Count -gt 0) {是否必要,因为工作簿不能包含零个工作表。 -
@Jeeped 我认为你是对的。正如本文(gallery.technet.microsoft.com/office/…),“一个最小的 Excel XLSX 包文件”应该包括 1 个强制性工作表。
标签: excel powershell