2015-04-28 109 views
1

您好,感謝您在這個問題上的時間,我正在嘗試根據用戶在Excel中選擇的選項更改活動打印機。但是我遇到了一些麻煩。出於某種原因,它一直給我同樣的錯誤。c#設置打印機

「型 '異常System.Runtime.InteropServices.COM' 的異常出現在DailyReport.dll但在用戶代碼異常 從HRESULT沒有處理:0X800A03EC」

我已經一直在搜索這個錯誤,我很難找到任何東西,我找到了一個鏈接COM Exception,他們提供了一個鏈接到另一個網站,但似乎當我嘗試去那個網站它不打開。

我曾嘗試:

xlApp.ActivePrinter = "CORPPRT58-Copier Room on RR-PS1:"; 

xlApp.ActivePrinter = "\\RR-PS1\CORPPRT58-Copier Room"; 

xlApp.ActivePrinter = "CORPPRT58-Copier Room on RR-PS1"; 

我已經檢查,以確保打印機被安裝,它是。如果有人能指出我正確的方向,那將是非常感謝!

+0

第二個將不會因爲斜槓的工作,你將需要使用xlApp.ActivePrinter = ** @ **「\\ RR-PS1 \ CORPPRT58-複印機室」; Windows中顯示的打印機名稱是什麼? –

+0

我想你會不得不逃避那些反斜槓 –

+0

它說「CORPPRT58複印機室RR-PS1」 – user3120232

回答

0

正確答案是(即):

xlApp.ActivePrinter = "\\\\RR-PS1\\CORPPRT58-Copier Room on Ne00:"; 

一個重要部分是「Ne00:」這是在其上該打印機可以發現的端口。這在每臺計算機上都不相同,可以在登錄處找到HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices

另一個問題是串聯字符串'on'。在使用英文excel時,這可能是有效的,但它被翻譯成其他語言!

我有同樣的問題,但不會有太多的例子完成我能找到所以這裏是我的:

// Open excel document 
var path = @"c:\path\to\my\doc.xlsx"; 

Microsoft.Office.Interop.Excel.Application _xlApp; 
Microsoft.Office.Interop.Excel.Workbook _xlBook; 
_xlApp = new Microsoft.Office.Interop.Excel.Application(); 
_xlBook = _xlApp.Workbooks.Open(path); 
_xlBook.Activate(); 

var printer = @"EPSON LQ-690 ESC/P2"; 
var port = String.Empty; 

// Find correct printerport 
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(path)) 
{ 
    if (key != null) 
    { 
     object value = key.GetValue(printer); 
     if (value != null) 
     { 
      string[] values = value.ToString().Split(','); 
      if (values.Length >= 2) port = values[1]; 
     } 
    } 
} 

// Set ActivePrinter if not already set 
if (!_xlApp.ActivePrinter.StartsWith(printer)) 
{ 
    // Get current concatenation string ('on' in enlgish, 'op' in dutch, etc..) 
    var split = _xlApp.ActivePrinter.Split(' '); 
    if (split.Length >= 3) 
    { 
     _xlApp.ActivePrinter = String.Format("{0} {1} {2}", 
      printer, 
      split[split.Length - 2], 
      port); 
    } 
} 

// Print document 
_xlBook.PrintOutEx(); 

這是迄今爲止完美的,因爲我不知道任何其他的翻譯。如果'on'被空格翻譯,則上面將失敗。但我猜測該解決方案將適用於大多數客戶。您可以通過查看ActivePrinter的正確值輕鬆獲取當前串聯字符串。

更爲失敗的方法是去除打印機名稱和分配的端口,剩下的是串聯字符串。但是,您必須遍歷所有安裝的打印機並檢查匹配。

我個人是它檢查是否安裝在系統上的打印機另一項測試:

if(PrinterSettings.InstalledPrinters.Cast<string>().ToList().Contains(printer)) { 
    //Set active printer... 
}