用于将文件另存为现有脚本的对话框

时间:2017-11-13 20:00:25

标签: excel powershell scripting dialog save-as

我有以下代码,但我试图通过动态对话框提示用户将输出文件“另存为”。

$pathtsv = "c:\test.txt"
$pathxlsx = "c:\NBP ESP-152 REV F TEMPLATE.xlsx"

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true 

$Workbook = $Excel.Workbooks.Open($pathxlsx) # Open Template
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv) # Open text file in excel

$temp = $excel.Workbooks.Item(2)  #select workbook with text
$temp = $temp.Worksheets.Item(1) #select text worksheet
$CopyRange = $temp.Range("A1:G8") #set range
$CopyRange.Copy()  #copy data

$workbooksheet = $Workbook.Worksheets.Item(1)#sets doc to copy to
$Workbooksheet.activate()
$PasteRange = $workbooksheet.Range("A3:J10") #sets range
$workbooksheet.Paste($PasteRange)#paste data

#save and close the workbook
$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()

所以我尝试添加:

$SaveFileDialog = New-Object windows.forms.savefiledialog   
    $SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory() 

但它似乎没有用。不知道为什么,也许是因为我仍然对PowerShell脚本编写新手。我只想在保存对话框中结束它,没关系。我必须切掉原件的末端吗? (IE。这会被删除吗?

$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()

1 个答案:

答案 0 :(得分:1)

你需要做一些事情来完成这项工作。首先,添加对System.Windows.Forms的引用

Add-Type -AssemblyName System.Windows.Forms

复制/粘贴操作后,创建对话框并设置几个属性

$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()
$SaveFileDialog.Filter = 'All files (*.*)|*.*'

这是您在显示对话框时需要决定要执行的操作的位置。您是否允许用户取消,如何处理空路径,不正确的扩展等...为了示例,我将继续显示它直到选择路径。我并不赞同这是一个不错的选择。

$dialogResult = $null
while($dialogResult -ne "OK"){
    $dialogResult = $SaveFileDialog.ShowDialog()
}

然后,您可以使用FileName属性访问所选路径,并对其执行和检查

$SaveFileDialog.FileName

将其传递给excel工作簿的SaveAs方法。有关此方法https://stackoverflow.com/a/25289878/3594883

的详细信息,请参阅此答案
$WorkBook.SaveAs($SaveFileDialog.FileName, 51, [Type]::Missing, [Type]::Missing, $false, $false, 1, 2)

最后关闭你的工作簿并取得优异成绩。执行清理等。