c# excel print 打印 将所有列调整为一页

excel有时候列数比较多,行数也比较多,转换成xps文档的时候,一般是通过打印来实现。

由于打印的范围限制,所以会出现本来在一行的数据,由于列数比较多,溢出范围,被打印到两页了。

为解决这个问题,需要设置一下sheet的缩放。

1.测试缩放在excel程序中:

在excel程序中有打印设置,如图(默认是无缩放的):

设置缩放(将所有列调整为一页),如图:

经过测试,这样设置后的打印效果,同一行的数据打印后在同一页了。

2.c#代码实现:

代码实现的方式是设置WorkSheet的PageSetup.FitToPagesTall属性。

测试代码如下:

 1  Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
 2                         Type tp = app.GetType();
 3                         Microsoft.Office.Interop.Excel.Workbooks workBook = app.Workbooks;
 4                         Type elType = workBook.GetType();
 5                         object objelName = sourceFile;
 6                         Microsoft.Office.Interop.Excel.Workbook ebook = (Microsoft.Office.Interop.Excel.Workbook)elType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, workBook, new Object[] { objelName, true, true });
 7                         Object missing = System.Reflection.Missing.Value;
 8                         for (int i = 0; i < ebook.Worksheets.Count; i++)
 9                         {
10                             Worksheet ws = ebook.Worksheets[i + 1];
11                             ws.PageSetup.Orientation = XlPageOrientation.xlPortrait;//页面方向竖向
12                             ws.PageSetup.Zoom = false;
13                             ws.PageSetup.FitToPagesWide = 1;
14                             ws.PageSetup.FitToPagesTall = false;
15                         }
16                         ebook.PrintOut(missing, missing, missing, missing, missing, true, missing, xpsFile);
17                         tp.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, app, null);
18                         workBook.Close();
19                         app.Quit();
View Code

 

经验证,可行。

感谢每一位阅读此篇文章的人,希望可以帮到你。

 

posted @ 2016-06-30 15:28  灰主流  阅读(3560)  评论(2编辑  收藏  举报