简体   繁体   English

如何为Excel文件“另存为”对话框指定默认目录?

[英]How to specify the default directory for an Excel file SaveAs dialog?

I have a button that the user presses and sends a grid to Excel, and it's saving the file in a directory that I don't want the user to have access to. 我有一个按钮,用户可以按下该按钮并将网格发送到Excel,它将文件保存在我不希望用户访问的目录中。 (It's a hidden share) It then opens the file immediately for the user to view. (这是一个隐藏的共享)然后立即打开文件供用户查看。

I'm using the Microsoft.Office.Interop.Excel namespace, so I'm using an Excel Application and Workbook. 我正在使用Microsoft.Office.Interop.Excel命名空间,所以我正在使用Excel应用程序和工作簿。

I want the application to open the file from the directory, but if the user chooses to save the file using SaveAs (I would prefer that if the user clicked Save, that it treated it as a new file and opened the SaveAs Dialog), I would like the initial directory to be something like C:. 我希望应用程序从目录中打开文件,但是如果用户选择使用SaveAs保存文件(我希望如果用户单击Save,它将其视为新文件并打开SaveAs对话框),希望初始目录类似于C:。

Here is a bit of the relevant code: 以下是一些相关代码:

Public Sub sendToExcel()

        'Code here that exports data to Excel

        Dim xlApp As Excel.Application = New Excel.Application()
        Dim xlWorkbook As Excel.Workbook = xlApp.Workbooks.Open(filePath)

        xlApp.Visible = True

End Sub

The most obvious thing I've tried is this: 我尝试过的最明显的事情是:

xlApp.DefaultFilePath = "C:\\"

This seems to only work if the file is new (hasn't been saved). 这似乎仅在文件是新文件(尚未保存)时才起作用。

Any suggestions? 有什么建议么?

Does the file have to be saved in that hidden share? 是否必须将文件保存在该隐藏共享中?

If not, you could save it in the user's temporary folder using the Path.GetTempFileName() and open it with Excel from there. 如果没有,您可以使用Path.GetTempFileName()将其保存在用户的临时文件夹中, Path.GetTempFileName()从此处使用Excel将其打开。

That way, when they "Save As", they will only see the local temporary folder as the source. 这样,当他们“另存为”时,他们只会将本地临时文件夹视为源。

Of course, this works only if it is a desktop application. 当然,仅当它是桌面应用程序时,此方法才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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