使用PowerShell

时间:2015-08-15 01:32:42

标签: excel powershell

我正在尝试将包含多个工作表的Excel文件拆分为多个文件,并搜索此博客:Extract worksheets from Excel into separate files with PowerShell。我试过xls文件,它工作正常。但是当我尝试xlsx文件时,它只输出整个源文件,当我用Excel Application打开生成的文件时,每张工作表都作为默认工作表。我很难解决这个问题,但没有运气。我的测试代码就像打击一样:

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

1 个答案:

答案 0 :(得分:1)

为了与标准Excel实践保持一致,将工作表复制到无目的地将创建一个新工作簿,该工作表作为单独的工作表,该工作簿将是JS Fiddle

$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) {
        $Worksheet.Copy()
        $ExtractedFileName = $WorkbookName + "~~" + $Worksheet.Name + "." + $output_type 
        $Excel.ActiveWorkbook.SaveAs($ExtractedFileName, $FileFormat) 
        $Excel.ActiveWorkbook.Close

        write-Output "Created file: $ExtractedFileName"
    }
} 

$Workbook.Close() 
$Excel.Quit() 
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
Stop-Process -Name EXCEL
Remove-Variable Excel

现在,它确实将工作簿传播到多个工作簿,每个工作簿都包含一个原始工作表的副本。我发现了一些谋杀Excel'命令进入尾端,以便以一个位于任务管理器进程选项卡中的恶意(和不可见)excel.exe结束。

ActiveWorkbook中删除最后一个excel.exe实例时,有一个很好的主题。