Home » excel » c# – How to get Range (Print Area) from Excel?

c# – How to get Range (Print Area) from Excel?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I made an Excel Add In, that has to export the print area as an image. It works fine, if I set the print area manually from the program (“Excel.Range range = sheet.Range[“A1”, “E5″]”), but I need to set the print area in Excel and export that area as an image. Does anybody has an idea how to get the print area I set in Excel?

public static void Save(RibbonControlEventArgs e)
{
    Excel.Window window = e.Control.Context;

    Excel.Worksheet sheet = ((Excel.Worksheet)window.Application.ActiveSheet);

    Excel.Range range = sheet.Range["A1", "E5"];

    range.CopyPicture(Excel.XlPictureAppearance.xlPrinter, Excel.XlCopyPictureFormat.xlPicture);

    range.Copy(Type.Missing);

    string fileName = @"U:\test.jpg";

    if (Clipboard.GetDataObject() != null)
    {
        IDataObject data = Clipboard.GetDataObject();

        Image image = (Image)data.GetData(DataFormats.Bitmap, true);

        image.Save(fileName, ImageFormat.Jpeg);
    }

    MessageBox.Show("Save successful!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
How to&Answers:

try the following code:

sheet.PageSetup.PrintArea;