In Loki We Trust The many projects of Lokkju, Inc

support
29Apr/103

Using Office Automation on IIS7

Though there are a lot of articles out there on office automation in dotnet (most of them telling you not to do it), there are very few covering how to get office automation up and running under IIS7 on a 64bit machine - and it is possible.

I needed to do this recently, and found one hint on how to get it working at http://forums.asp.net/t/1328690.aspx . They key is to use Process to launch the application you need, then attach to it.

Sample code in C#:


Microsoft.Office.Interop.Word.Application app = null;
Process proc = null;
Document doc = null;
try
{
ProcessStartInfo procinfo = new ProcessStartInfo(WORD_PATH, "");
procinfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
procinfo.CreateNoWindow = true;
procinfo.WindowStyle = ProcessWindowStyle.Hidden;
proc = Process.Start(procinfo);
proc.WaitForInputIdle();
app = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
if (app == null) { throw new Exception("Word not found"); }
app.Visible = false;
app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
#region Declare Params
object fileName = filename;
object ConfirmConversions = false;
object ReadOnly = true;
object AddToRecentFiles = Type.Missing;
object PasswordDocument = Type.Missing;
object PasswordTemplate = Type.Missing;
object Revert = Type.Missing;
object WritePasswordDocument = Type.Missing;
object WritePasswordTemplate = Type.Missing;
object Format = Type.Missing;
object Encoding = Type.Missing;
object Visible = false;
object OpenAndRepair = Type.Missing;
object DocumentDirection = Type.Missing;
object NoEncodingDialog = Type.Missing;
object XMLTransform = Type.Missing;
#endregion
doc = app.Documents.Open(ref fileName, ref ConfirmConversions, ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate, ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format, ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection, ref NoEncodingDialog, ref XMLTransform);
// DO WHATEVER YOU NEED TO HERE
}
finally
{
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
object OriginalFormat = Type.Missing;
object RouteDocument = Type.Missing;
try
{
((_Document)doc).Close(ref saveChanges, ref OriginalFormat, ref RouteDocument);
doc = null;
}
catch { }
try
{
((Microsoft.Office.Interop.Word._Application)app).Quit(ref saveChanges, ref OriginalFormat, ref RouteDocument);
app = null;
}
catch { }
try
{
proc.Kill();
}
catch { }
}

notice
store
   
search