C# Excel互操作打印

C# Excel互操作打印,c#,excel,printing,interop,C#,Excel,Printing,Interop,我需要使用以下打印设置打印excel工作表的选定区域(使用Range.Select()选择): 打印机:Microsoft XPS文档编写器 打印选择 横向定位 A4 正常页边距 一页纸 如何使用_Worksheet.PrintOut或_Worksheet.PrintOutEx实现这一点 提前谢谢 试试这个(试过并测试过) 我假设您已经设置了对Excel的引用,并且已经声明了您的对象,如 Microsoft.Office.Interop.Excel.Application xlexcel; Mi

我需要使用以下打印设置打印excel工作表的选定区域(使用Range.Select()选择):

打印机:Microsoft XPS文档编写器
打印选择
横向定位
A4
正常页边距
一页纸

如何使用_Worksheet.PrintOut或_Worksheet.PrintOutEx实现这一点

提前谢谢

试试这个(试过并测试过)

我假设您已经设置了对Excel的引用,并且已经声明了您的对象,如

Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Range xlRange;
object misValue = System.Reflection.Missing.Value;
这将在代码的后面部分进行介绍

// Get the current printer
string Defprinter = null;
Defprinter = xlexcel.ActivePrinter;

// Set the printer to Microsoft XPS Document Writer
xlexcel.ActivePrinter = "Microsoft XPS Document Writer on Ne01:";

// Setup our sheet
var _with1 = xlWorkSheet.PageSetup;
// A4 papersize
_with1.PaperSize = Excel.XlPaperSize.xlPaperA4;
// Landscape orientation
_with1.Orientation = Excel.XlPageOrientation.xlLandscape;
// Fit Sheet on One Page 
_with1.FitToPagesWide = 1;
_with1.FitToPagesTall = 1;
// Normal Margins
_with1.LeftMargin = xlexcel.InchesToPoints(0.7);
_with1.RightMargin = xlexcel.InchesToPoints(0.7);
_with1.TopMargin = xlexcel.InchesToPoints(0.75);
_with1.BottomMargin = xlexcel.InchesToPoints(0.75);
_with1.HeaderMargin = xlexcel.InchesToPoints(0.3);
_with1.FooterMargin = xlexcel.InchesToPoints(0.3);

// Print the range
xlRange.PrintOutEx(misValue, misValue, misValue, misValue, 
misValue, misValue, misValue, misValue);

// Set printer back to what it was
xlexcel.ActivePrinter = Defprinter;

要使“一页上的调整工作表”正常工作,我们还应将Zoom属性设置为false

//一页纸

_with1.FitToPagesWide = 1;

_with1.FitToPagesTall = 1;

_with1.Zoom = False;

非常感谢你!但是你怎么知道“在Ne01上”?你可以使用
Defprinter=xlexcel.ActivePrinter然后在即时窗口中打印它。该代码将告诉您活动打印机是什么。要测试它,请将打印机更改为XPS,然后运行上述代码。我找到了以下方法来检测要使用的Ne端口:。除了页面设置。缩放必须设置为false,以使FitPagesWide/Tall工作并使用范围。ExportAsFixedFormat(XlFixedFormatType.xlTypeXPS,outputPath);而不是PrintOutEx。也许您可以更新上面的代码:)如果用户希望从第3页打印到第7页,如何自动执行。是否可以添加_with1.StartPage和_with1.EndPage??谢谢,我有一个excel文件,我想在打印excel文件时自动更换打印机托盘。我怎么能做到。Tks