正確答案是(即):
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...
}
第二個將不會因爲斜槓的工作,你將需要使用xlApp.ActivePrinter = ** @ **「\\ RR-PS1 \ CORPPRT58-複印機室」; Windows中顯示的打印機名稱是什麼? –
我想你會不得不逃避那些反斜槓 –
它說「CORPPRT58複印機室RR-PS1」 – user3120232