How to disable popups when opening a file using Microsoft.Office.Interop

↘锁芯ラ 提交于 2019-11-28 08:21:44
dotNetkow

See my answer here.

Basically, you disable all alerts via the "Display Alerts" method:

Microsoft.Office.Interop.[OFFICE_APP].Application app = new Microsoft.Office.Interop.[OFFICE_APP].Application();
app.DisplayAlerts = false;

where [OFFICE_APP] is the name of the Office program you're using, such as Word, Excel, etc.

Uriel Fernandez

Here is another alternative to prevent the Security message asking you to allow macros.

I read this article from MSDN and figured out the following code:

Application wordApp = new Application()
{
    Visible = false,
    AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable
};

Since a copy of the file is made before opening it I don't have to change the AutomationSecurity back to the default setting.

Azhar

Try this:

Microsoft.Office.Interop.Word.Application appWord = new 
Microsoft.Office.Interop.Word.Application();

appWord.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;

This will disable the popups.

Adding a note: for some file formats (I tested .XLS, but probably others too) that are password protected, app.DisplayAlerts = false will NOT bypass the password dialog.

In this situation, you can simply pass a fake password on open, which will throw an error. Catch it if you want.

var app = new Application();
app.DisplayAlerts = false;
var workbook = app.Workbooks.Open(filePath, "fakePassword"); // Bypasses dialog, throws error

In this situation the error thrown is:

System.Runtime.InteropServices.COMException: The password you supplied is not correct. Verify that the CAPS LOCK key is off and be sure to use the correct capitalization.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!