如何从 Excel 获取范围(打印区域)?

How to get Range (Print Area) from Excel?

我制作了一个 Excel 加载项,它必须将打印区域导出为图像。它工作正常,如果我从程序中手动设置打印区域 ("Excel.Range range = sheet.Range["A1", "E5"]"),但我需要在 Excel 中设置打印区域并导出该区域作为图像。有人知道如何获取我在 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);
}

试试下面的代码:

sheet.PageSetup.PrintArea;