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

时间:2023-03-09 01:44:38
c# excel print 打印 将所有列调整为一页

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

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

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

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

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

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

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

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

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

2.c#代码实现:

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

测试代码如下:

  Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Type tp = app.GetType();
Microsoft.Office.Interop.Excel.Workbooks workBook = app.Workbooks;
Type elType = workBook.GetType();
object objelName = sourceFile;
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 });
Object missing = System.Reflection.Missing.Value;
for (int i = ; i < ebook.Worksheets.Count; i++)
{
Worksheet ws = ebook.Worksheets[i + ];
ws.PageSetup.Orientation = XlPageOrientation.xlPortrait;//页面方向竖向
ws.PageSetup.Zoom = false;
ws.PageSetup.FitToPagesWide = ;
ws.PageSetup.FitToPagesTall = false;
}
ebook.PrintOut(missing, missing, missing, missing, missing, true, missing, xpsFile);
tp.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, app, null);
workBook.Close();
app.Quit();

经验证,可行。

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