简体   繁体   English

从ASP MVC控制器运行Word时保持获取InteropServices.COMException

[英]Keep Getting InteropServices.COMException when running Word from ASP MVC Controller

I get the error the remote procedure call failed HRESULT: 0x800706BE exception when running Microsoft.Interop.Word from a controller in my ASP .NET MVC application. 我从ASP.NET MVC应用程序中的控制器运行Microsoft.Interop.Word时,收到远程过程调用失败的HRESULT:0x800706BE异常的错误。 The strange thing is that if I debug the application and run it step by step, no exception is thrown. 奇怪的是,如果我调试应用程序并逐步运行它,则不会引发异常。 I haven't been able to understand the few documentation I've found on microsoft about this exception. 我一直无法理解我在Microsoft上找到的有关此异常的一些文档。 I read is has to do with Word closing the sockets when it's called, but I'm at a loss to understand anything about it, so I hope someone may know what the problem may be. 我读到的内容与Word在调用时关闭套接字有关,但是我不知所措,无法理解它,所以我希望有人可能知道问题所在。 The exception is always thrown at a specific line of my code (I've commented where it fails): 总是在我的代码的特定行抛出异常(我在失败的地方注释了):

//
    // GET /Asistencia/PrintDocentes
    public ActionResult PrintDocentes(int IdCurso)
    {
        List<AsistenciaDocentesViewModel> materias = new Metodos.Entidades().getListadoProfesores(IdCurso);
        List<int> compartidas = new List<int>();
        compartidas = materias.GroupBy(t => t.IdMateriasCursos).Where(t => t.Count() > 1).Select(t => t.Key).ToList();
        List<string> catedrasCompartidas = new List<string>();
        catedrasCompartidas= materias.Where(s => compartidas.Any(t=> t.Equals(s.IdMateriasCursos))).Select(r => r.NombresMaestro).ToList();

        string document = "asistenciaDocentes.docx";
        string uploadsFolder = HostingEnvironment.MapPath("~/App_Data/Docs");
        string imageFolder = HostingEnvironment.MapPath("~/Images/Docs");
        string[] encabezado = { "logoCideAsistencia.jpg", "logoSegobAsistencia.jpg", "logoPFAsistencia.jpg", "logoDiplomadoAsistencia.jpg" };
        string archivo = Path.Combine(uploadsFolder, @document);
        ApWord = new Word.Application();
        docAsistencia = ApWord.Documents.Add(ref opc, ref opc, ref opc, ref opc);
        ApWord.Visible = true;
        docAsistencia.PageSetup.RightMargin = (float)100;
        docAsistencia.PageSetup.LeftMargin = (float)60;
        foreach (Word.Section section in ApWord.ActiveDocument.Sections)
        {
            Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            for (int i = 0; i < encabezado.Length; i++)
            {
                headerRange.Collapse(Word.WdCollapseDirection.wdCollapseStart);
                string path = Path.Combine(imageFolder, encabezado[i]);
                Word.InlineShape map = headerRange.InlineShapes.AddPicture(path);
                if (i == 0) { map.Height = 48; map.Width = 39; } /*********
*********************This is the line that throws the exception ********/
                if (i == 1) { map.Width = 263; map.Height = 39; }
                if (i == 2) { map.Width = 141; map.Height = 26; }
                headerRange.Move(Word.WdUnits.wdCharacter);
                headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
                if (i == 2) break;

            }

            Word.Shape titulo = docAsistencia.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,60, 5, 300, 50, ref opc);
            titulo.TextFrame.TextRange.Text = "DIPLOMADO EN MANDO POLICIAL 2015\nLista de Asistencia de profesores\n";
            titulo.Line.Visible = MsoTriState.msoFalse;
            titulo.TextFrame.TextRange.Font.Name = "Cambria";
            titulo.TextFrame.TextRange.Font.Size = 16;
            titulo.TextFrame.TextRange.Font.Bold = 1;
            titulo.TextFrame.TextRange.Font.Italic = 1;


            headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            Word.InlineShape map2 = headerRange.InlineShapes.AddPicture(Path.Combine(imageFolder, encabezado[3]));
            map2.Height = 106;
            map2.Width = 137;


        }
        foreach(AsistenciaDocentesViewModel item in materias)
        {
        Word.Paragraph grupo1 = docAsistencia.Paragraphs.Add(ref opc);
        grupo1.Range.Font.Name = "Arial";
        grupo1.Range.Font.Size = 14;
        grupo1.Range.Font.Bold = 1;
        grupo1.Range.InsertAfter("Semana\t" + item.Semana);
        Word.Paragraph grupo2 = docAsistencia.Paragraphs.Add();
        grupo2.Range.InsertAfter("Sede\t" + item.Sede);
        Word.Paragraph grupo3 = docAsistencia.Paragraphs.Add();
        grupo3.Range.InsertAfter("Grupo\t" + item.Grupo);
        Word.Paragraph grupo4 = docAsistencia.Paragraphs.Add();
        docAsistencia.Words.Last.InsertBreak(Word.WdBreakType.wdLineBreak);
        grupo4.Range.InsertAfter("Fecha\t" + item.Fecha);
        Word.Paragraph grupo5 = docAsistencia.Paragraphs.Add();
        grupo5.Range.InsertAfter("Día\t" + item.Dia);
        Word.Paragraph grupo6 = docAsistencia.Paragraphs.Add();
        grupo6.Range.InsertAfter("Horario\t" + item.HorarioInicio + " - " + item.HorarioFin);
        Word.Paragraph grupo7 = docAsistencia.Paragraphs.Add();
        grupo7.Range.InsertAfter("compartir");

        if (compartidas.Contains(item.IdMateriasCursos))
        {
            List<AsistenciaDocentesViewModel> compartir = materias.Where(t => t.IdMateriasCursos.Equals(item.IdMateriasCursos)).ToList();
            List<string> catedras = compartir.Select(t => t.NombresMaestro).ToList();
            List<string> catedras_aImprimir = catedras.Where(t => !t.Equals(item.NombresMaestro)).ToList();
            foreach (string catedra in catedras_aImprimir)
            {
                Word.Paragraph grupo8 = docAsistencia.Paragraphs.Add();
                grupo8.Range.InsertAfter(catedra);

            }
            docAsistencia.Words.Last.InsertBreak(Word.WdBreakType.wdLineBreak);
        }
        Word.Paragraph grupo9 = docAsistencia.Paragraphs.Add();
        grupo9.Range.InsertAfter("Módulo");
        Word.Paragraph grupo10 = docAsistencia.Paragraphs.Add(); 
        grupo10.Range.InsertAfter(item.Modulo);
        Word.Paragraph grupo11 = docAsistencia.Paragraphs.Add();
        grupo11.Range.InsertAfter("Materia");
        Word.Paragraph grupo12 = docAsistencia.Paragraphs.Add();
        grupo12.Range.InsertAfter(item.Materia);
        Word.Paragraph grupo13 = docAsistencia.Paragraphs.Add();
        grupo13.Range.InsertAfter("Profesor");
        Word.Paragraph grupo14 = docAsistencia.Paragraphs.Add();
        grupo14.Range.InsertAfter(item.NombresMaestro);
        Word.Paragraph grupo15 = docAsistencia.Paragraphs.Add();
        grupo15.Range.InsertAfter("Firma:______________________________________________________");

        docAsistencia.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);
        }
        docAsistencia.SaveAs2(archivo, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc,
            ref opc, ref opc, ref opc, ref opc, ref opc, ref opc);
        docAsistencia.Close();
        Marshal.FinalReleaseComObject(ApWord);
        Marshal.FinalReleaseComObject(docAsistencia);
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        return RedirectToAction("VerRecursos", new { file = document });

    }

Please help, I haven't worked with Interop before so I really can't guess what's wrong, I thought maybe the two for cycles may cause the problem, but I really have no idea. 请帮助,我之前没有与Interop合作过,所以我真的无法猜测出了什么问题,我以为两个周期可能会导致问题,但是我真的不知道。

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment. Microsoft当前不建议也不支持任何无人参与的非交互客户端应用程序或组件(包括ASP,ASP.NET,DCOM和NT Services)中的Microsoft Office应用程序自动化,因为Office可能表现出不稳定的行为和/在此环境中运行Office时出现死锁或死锁。

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. 如果要构建在服务器端上下文中运行的解决方案,则应尝试使用对无人值守执行安全的组件。 Or, you should try to find alternatives that allow at least part of the code to run client-side. 或者,您应该尝试找到允许至少部分代码在客户端运行的替代方法。 If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. 如果您从服务器端解决方案中使用Office应用程序,则该应用程序将缺少许多成功运行所需的功能。 Additionally, you will be taking risks with the stability of your overall solution. 此外,您将承担整体解决方案稳定性的风险。 You can read more about that in the Considerations for server-side Automation of Office article. 您可以在“ 服务器端Office自动化注意事项”文章中阅读有关此内容的更多信息。

Consider using Open XML SDK, see Welcome to the Open XML SDK 2.5 for Office for more information. 考虑使用Open XML SDK,有关更多信息,请参阅欢迎使用Office Open XML SDK 2.5 Also you may find third-party components that are designed for the server-side execution. 另外,您可能会发现专门为服务器端执行而设计的第三方组件。

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

相关问题 将项目添加到 ObservableCollection 时出现 InteropServices.COMException - InteropServices.COMException when adding item to ObservableCollection InteropServices.COMException - InteropServices.COMException 为什么我在尝试从 C# 启动 QTP 时收到 InteropServices.COMException? - Why do I get an InteropServices.COMException when attempting to launch QTP from C#? C# AutoIt InteropServices.COMException 错误 - C# AutoIt InteropServices.COMException error 从页面调用静态异步方法导致 InteropServices.COMException 错误 - Calling a static async method from a Page results in InteropServices.COMException error 间歇性的“ InteropServices.COMException / ForwardCallToInvokeMember”在范围单元格上访问Value2 - Intermittent “InteropServices.COMException / ForwardCallToInvokeMember” accessing Value2 on Range cell com 异常 excel InteropServices.COMException - c# - com exception excel InteropServices.COMException - c# 如何在不安装Excel的情况下修复InteropServices.COMException? - How can I fix InteropServices.COMException without installing Excel? 为什么使用此代码会得到“ InteropServices.COMException / ForwardCallToInvokeMember”? - Why would I get, “InteropServices.COMException / ForwardCallToInvokeMember” with this code? InteropServices.COMException(0x800A1066):在Teamcity下命令失败 - InteropServices.COMException (0x800A1066): Command failed under Teamcity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM