Home » excel » c# – Excel automation: Any way of knowing how many pages a sheet will be printed out on?

c# – Excel automation: Any way of knowing how many pages a sheet will be printed out on?

Posted by: admin April 23, 2020 Leave a comment

Questions:

Some times the sheets are too big to be printed out, so I would like avoid printing it, if this is the case.

My current program:

  1. Opens an excel-document
  2. Copies the first sheet
  3. Creates a new document
  4. Insert text and formulas in the new document
  5. Makes autofit on the columns when the text is shown
  6. Print text (not implemented yet)
  7. Makes autofit on the columns when the formulas are shown
  8. Print formulas (not implemented yet)

The reason for the copy/paste is to be able to autofit the columns even if the document/sheet/cell is write-protected with password.

But I would like to avoid printing it if, for example, the current sheet fills more than 100 pages. How can I check this?

        // Open Excel
        xlApp = new Excel.ApplicationClass();
        xlApp.Visible = true;

        // Open document
        xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

        // Select the sheet we want to copy
        Excel.Sheets xlSheets = null;
        xlSheets = xlWorkBook.Sheets as Excel.Sheets;
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        // Mark all cells and copy
        xlWorkSheet.UsedRange.Copy(misValue);

        // Make a new empty document
        Excel.Workbook xlWorkBook2;
        xlWorkBook2 = xlApp.Workbooks.Add(misValue);

        // Select the first sheet and insert
        Excel.Worksheet xlWorkSheet2;
        xlWorkSheet2 = (Excel.Worksheet)xlWorkBook2.Worksheets.get_Item(1);
        xlWorkSheet2.Name = "temp";

        // Just copies to range starting at cell A1
        Excel.Range range = (Excel.Range)((Excel.Worksheet)xlWorkSheet2).Cells[1, 1];
        range.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteValues, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, misValue, misValue);
        range.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteFormulas, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, misValue, misValue);

        // Adjust width of cells (autofit must be called on a column)
        xlWorkSheet2.Columns.AutoFit();

        // Show formulas
        xlWorkSheet2.Application.ActiveWindow.DisplayFormulas = true;
        xlWorkSheet2.Columns.AutoFit();

        xlWorkSheet2.PrintPreview(misValue);

        // Close Excel
        xlWorkBook2.Close(false, false, misValue);
        xlWorkBook.Close(false, false, misValue);
        xlApp.Quit();
How to&Answers:

This post answered it. In my code it would be implemented as:

int numberOfPages = xlWorkSheet2.PageSetup.Pages.Count;

And it works.