我在使用 excel interop 打印 excel 文档时遇到了同样的异常。
使用 MS Word:-
document.Application.ActivePrinter = "Brother MFC.. Printer"; // Works without exception
但是使用 MS Excel :-
document.Application.ActivePrinter = "Brother MFC.. Printer"; // throws COM exception
以下是使用 office interop 打印任何 office(MS Word、MS Excel、PS Powerpoint)文档的通用功能。
void PrintToPrinter(dynamic app, dynamic document, string printer, int numberOfCopies)
{
bool PrintToFile = false;
// Trying to print document without activation throws print exception
document.Activate();
// The only way to change printer is to set the default printer of document or of application
// Remember the active printer name to reset after printing document with intended printer
oldPrinterName = document.Application.ActivePrinter;
for (int retry = 0; retry < retryLimit; retry++)
{
try
{
if (!GetActivePrinter(document).Contains(printer))
{
try
{
document.Application.ActivePrinter = printer;
docPrinterChanged = true;
}
catch (Exception)
{
try
{
app.ActivePrinter = printer;
appPrinterChanged = true;
}
catch (Exception)
{
continue;
}
}
}
object oMissing = System.Reflection.Missing.Value;
document.PrintOut(
true, // Background
false, // Append overwrite
oMissing, // Page Range
oMissing, // Print To File - OutputFileName
oMissing, // From page
oMissing, // To page
oMissing, // Item
numberOfCopies, // Number of copies to be printed
oMissing, //
oMissing, //
PrintToFile, // Print To file
true // Collate
);
break;
}
catch (Exception)
{
continue;
}
}
try
{
if(docPrinterChanged)
document.Application.ActivePrinter = oldPrinterName;
else if(appPrinterChanged)
app.ActivePrinter = oldPrinterName;
}
catch (Exception)
{
}
}
private static string GetActivePrinter(dynamic document)
{
string activePrinter = document.Application.ActivePrinter;
if (activePrinter.Length >= 0)
return activePrinter;
return null;
}
将上述功能用于 MS Excel 时,我会更新打印机名称,如下所示。从 MS Excel 实例将打印机名称传递给上述函数时,我使用
bool IFilePrint.PrintFile(string fullFileName, string printerName, int numberOfCopies)
{
// .......
Excel.Workbook document = null;
try
{
document = this.Application.Workbooks.Open(fullFileName);
}
catch
{
document = null;
}
string portNumber = null;
// Find correct printerport
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(fullFileName))
{
if (key != null)
{
object value = key.GetValue(printerName);
if (value != null)
{
string[] values = value.ToString().Split(',');
if (values.Length >= 2) port = values[1];
}
}
}
// Get current concatenation string ('on' in en, 'auf' in de, etc..)
var split = this.Application.ActivePrinter.Split(' ');
if (split.Length >= 3)
printerName = String.Format("{0} {1} {2}", printerName, split[split.Length - 2], port);
PrintToPrinter(this.Application, document, printerName, numberOfCopies);
// ...........
}
catch (Exception)
{ }
result = true;
return result;
}
可以对此进行进一步检查:
1) 使用 PrinterSettings 类检查目标打印机是否存在。
2) (打印到文件)检查预期的打印选项是否是 To PDF/ To XPS / FAX 等。