Use Excel Interop to grab image of Excel chart without writing to disk or using the clipboard

后端 未结 2 1772
太阳男子
太阳男子 2021-01-14 23:53

The interface to the chart object in Excel only allows access to the image representing the chart through two methods:

  • export, which saves the image to a file<
2条回答
  •  爱一瞬间的悲伤
    2021-01-15 00:21

    SpreadsheetGear for .NET can load an Excel workbook and return an image from a chart with a few lines of code:

    namespace GetChartImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Open the workbook.
                var workbook = SpreadsheetGear.Factory.GetWorkbook(@"t:\tmp\Chart.xlsx");
                // Get a chart named "Chart 1" on the sheet named "Sheet1".
                var chart = workbook.Worksheets["Sheet1"].Shapes["Chart 1"].Chart;
                // Get a System.Drawing.Bitmap image of the chart.
                var bitmap = new SpreadsheetGear.Drawing.Image(chart).GetBitmap();
                // Save it to a file and launch just to see that it worked.
                bitmap.Save(@"t:\tmp\Chart.png", System.Drawing.Imaging.ImageFormat.Png);
                System.Diagnostics.Process.Start(@"t:\tmp\Chart.png");
            }
        }
    }
    

    SpreadsheetGear does not support every Excel charting feature (yet) but you can see a representative sample of what it can do in the live ASP.NET "Dynamic Chart Gallery" sample here, or you can download the free trial here and try it yourself.

    Disclaimer: I own SpreadsheetGear LLC

提交回复
热议问题