Search code examples
c#excelpngresolution

c# chart.object from excel as .png low resolution


I have created an excel file and want to export its contents as a png or jpeg file.

Unfortunately the quality of the image is really low.

Is there a solution to this? I wish a really high resolution picture.

Thank you

My current code (from internet):

     Excel.Range xlRange = xlWorksheet5.get_Range("A1", "K30");
        xlRange.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlPicture);
        Excel.ChartObject chartObj;
        chartObj = xlWorksheet5.ChartObjects().Add(xlRange.Left, xlRange.Top, xlRange.Width, xlRange.Height);
        chartObj.Activate(); 
        string path_image = path + "\\image.png";
        Excel.Chart chart = chartObj.Chart;
        chart.Paste();
        chart.Export(path_image);

Solution

  • Try this. You'll need to put a [STAThread] attribute over the entry point of whatever thread you run this on.

        //This first copy/paste is to convert from chart to image
        chartObj.CopyPicture();
        xlWorksheet5.Paste();
    
        //This image has decent resolution
        xlWorksheet5.Shapes.Item(xlWorksheet5.Shapes.Count).Copy();
    
        //Save the image
        System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
        enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(System.Windows.Clipboard.GetImage()));
        using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
        {
            enc.Save(outStream);
            System.Drawing.Image pic = new System.Drawing.Bitmap(outStream);
            pic.Save("image.png");
        }