正确答案是(即):
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