c# - 在活动 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完成后,我们应该如何关闭这个“应用程序的打印驱动程序主机”?
解决方案
推荐阅读
- javascript - 如何执行这两个 OnScrolls?
- google-analytics - GA BigQuery 导出 - COUNT(DISTINCT(fullVisitorId)) 与源/媒介多算
- c++ - unordered_map 不应该只有两个参数吗?
- c - c语言中使用fork()处理socket中多个客户端的逻辑问题
- timer - STM32F4上定时器和spi之间的中断优先级问题
- javascript - 在提交时将随机数插入隐藏字段
- javascript - 错误的 POST 请求和使用 Ajax 的 GET 没有返回值
- python - 如何将每个段落从 .docx 文件复制到 .csv 文件中的新行?
- json - 有什么好的方法可以在 Flutter 中向 JSON 发出 POST 请求吗?
- php - @OneToOne 和 @JoinColumn 产生类型的期望值...异常