3

I have xltx Excel's template, when I create (manually) new document from it and click File->Print in Excel first sheet fits on one page.

Than I create new document from my template with the help of ClosedXml:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClosedXML.Excel;

namespace ClosedXml1
{
    class Program
    {
        static void Main(string[] args)
        {
            var tXltx = "t.xltx";
            using (XLWorkbook workbook = new XLWorkbook(tXltx))
            {
                using (XLWorkbook newWb = new XLWorkbook())
                {
                    foreach (XLWorksheet worksheet in workbook.Worksheets.Reverse())
                    {
                        worksheet.CopyTo(newWb, worksheet.Name, 1);
                    }

                    newWb.SaveAs("new.xlsx");
                }
            }
        }
    }
}

When I open resulting document and open printing dialog (File->Print) first sheet doesn't fit on one page.

UPDATE1: XLWorksheet::CopyTo copies page setup from original template to resulting workbook. So, if xltx template has page setup FitToPages(1,1), resulting document will have the same page setup. Despite that, when I open printing preview of ClosedXml-generated sheet it doesn't fit one page. So, it is problem: original and resulting workbooks have the same page setup, but generated worksheet doesn't fit one page.


So there are questions:

  • What has to be copied from original template that resulting sheet fits one page?
  • Is there any way to accomplish it?

Workaround

Excel.Application excelApp = new Excel.Application();
Workbook original = excelApp.Workbooks.Open(originalFilename);
original.SaveAs(resultingFilename);                    
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
Evgeny Timoshenko
  • 3,119
  • 5
  • 33
  • 53

2 Answers2

4

You can check / set the options for this with

worksheet.PageSetup.PagesTall
worksheet.PageSetup.PagesWide
worksheet.PageSetup.FitToPages(1, 1)

(See the Documentation.)

Raidri
  • 17,258
  • 9
  • 62
  • 65
0

Yes, ClosedXml will loose these settings when performing CopyTo. A particular case is when PagesTall is set to empty, it must explicitly set to -1 on worksheet copy, otherwise ClosedXml will put it to 1.

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164