首页 > 解决方案 > 在活动 Word 文档上粘贴 Excel 范围会打开应用程序的打印驱动程序主机

问题描述

我正在实现一些代码以在 Word 文档中嵌入 Excel 工作表。Print driver host for applications在Word 上粘贴(特殊粘贴)复制 excel 范围时正在打开该过程。我创建了一些示例代码来重新创建问题。

private void button1_Click(object sender, EventArgs e)
{
     string path = @"C:\Users\Aps\Desktop\excelDoc.xlsx";
     Word.Document doc = GetActiveDocument();
     Type ExcelType = Type.GetTypeFromProgID("Excel.Application");
     dynamic ExcelInst = Activator.CreateInstance(ExcelType);
     excelapp = ExcelInst;
     excelapp.Visible = false;

     workbook = excelapp.Workbooks.Open(path, true);
     Excel.Worksheet sheet = workbook.Sheets[1];
     Excel.Range excelRange = sheet.Range["A1","E7"];
     sheet.Activate();
     excelRange.Copy();

     Word.Range wordRange = doc.Range();
     wordRange.InsertParagraphAfter();
     wordRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);

     // insert embedded worksheet
     wordRange.PasteSpecial(
         Link: false,
         DataType: Word.WdPasteDataType.wdPasteOLEObject,
         Placement: Word.WdOLEPlacement.wdInLine,
         DisplayAsIcon: false
     );
     CloseWorkbook();
}

private void CloseWorkbook()
{
    try
    {
        if (workbook != null)
        {
            workbook.RefreshAll();
            workbook.Close(SaveChanges: true);
        }
        if (excelapp != null)
        {
            var process = Process.GetProcessesByName("EXCEL").OrderByDescending(p => p.StartTime).First();
            if (!process.HasExited)
            {
                process.Kill();
            }
        }
    }
    catch
    {
        //Erorr handling
    }
}

private Word.Document GetActiveDocument()
{
    object word;
    Word.Document _activeDocument;

    try
    {
        word = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
        //If there is a running Word instance, it gets saved into the word variable
    }
    catch (Exception ex)
    {
        //If there is no running instance, it creates a new one
        Type type = Type.GetTypeFromProgID("Word.Application");
        word = System.Activator.CreateInstance(type);
    }

    Word.Application oWord = (Word.Application)word;
    _activeDocument = oWord.ActiveDocument;

    return _activeDocument;
}

在我的应用程序中,我使用了 MyStyles.dotx 文件,我们在其中存储了我们自己的单词字段样式。由于此应用程序应用程序的打印驱动程序主机未关闭问题,在使用 excel 嵌入功能后,似乎 MyStyles.dotx 文件未正确关闭,并且在下一次机器启动时,MyStyles.dotx 的副本正在打开。我尝试使用任务管理器手动关闭应用程序的打印驱动程序主机,然后在机器启动时重新打开 MyStyles.dotx 的问题不再存在。

为什么此应用程序的打印驱动程序主机在打开wordRange.PasteSpecial

有没有办法避免打开“应用程序的打印驱动程序主机”应用程序wordRange.PasteSpecial

如果不是,在excel嵌入word完成后,我们应该如何关闭这个“应用程序的打印驱动程序主机”?

标签: c#excelms-word

解决方案


推荐阅读