如何将Excel工作表导出为图像?

时间:2014-02-13 16:08:02

标签: c# excel

我正在试图从excel工作表生成图像。经过大量的研究,我使用了以下代码,但在某些时候我得到了一个例外:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    class Prueba
    {
        [STAThread]
        static void Main(string[] args)
        {
            var a = new Microsoft.Office.Interop.Excel.Application();

            try
            {
                Workbook w = a.Workbooks.Open(@"C:\SCRATCH\Libro2.xlsx");
                Worksheet ws = w.Sheets["Report"];
                ws.Protect(Contents: false);
                Range r = ws.Range["B2:H20"];
                r.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
                a.DisplayAlerts = false;

                // System.Runtime.InteropServices.COMException Excepción de HRESULT: 0x80010105 (RPC_E_SERVERFAULT)
                ChartObject chartObj = ws.ChartObjects().Add(r.Left, r.Top, r.Width, r.Height); 

                chartObj.Activate();
                Chart chart = chartObj.Chart;
                chart.Paste();
                chart.Export(@"C:\SCRATCH\image.JPG", "JPG");
                chartObj.Delete();
                w.Close(SaveChanges: false);
            } 
            finally
            {
                a.Quit();                
            }

        }
    }
}

我正在使用Office 2013,64位,Windows 7 64和.Net 4.5。

3 个答案:

答案 0 :(得分:3)

这在WinForms项目中对我有用:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using ios = System.Runtime.InteropServices;

namespace ClipBoardTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void ExportRangeAsJpg()
        {
            Excel.Application xl;

            xl = (Excel.Application)ios.Marshal.GetActiveObject("Excel.Application");

            if (xl == null)
            {
                MessageBox.Show("No Excel !!");
                return;
            }

            Excel.Workbook wb = xl.ActiveWorkbook;
            Excel.Range r = wb.ActiveSheet.Range["A1:E10"];
            r.CopyPicture(Excel.XlPictureAppearance.xlScreen,
                           Excel.XlCopyPictureFormat.xlBitmap);

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

                if (data.GetDataPresent(DataFormats.Bitmap))
                {
                    Image image = (Image)data.GetData(DataFormats.Bitmap, true);
                    this.pict1.Image = image;
                    image.Save(@"C:\_Stuff\test\sample.jpg",
                        System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                else
                {
                    MessageBox.Show("No image in Clipboard !!");
                }
            }
            else
            {
                MessageBox.Show("Clipboard Empty !!");
            }  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ExportRangeAsJpg();
        }



    }
}

对于控制台应用,您还需要查看:http://blog.another-d-mention.ro/programming/c/use-clipboard-copypaste-in-c-console-application/

答案 1 :(得分:2)

无需创建Chart对象。在CopyPicture()上调用Range会将图像放在系统剪贴板上。如果你愿意的话,你可以在两步之内完成它:

        Workbook w = a.Workbooks.Open(@"C:\SCRATCH\Libro2.xlsx");
        Worksheet ws = w.Sheets["Report"];
        ws.Protect(Contents: false);
        Range r = ws.Range["B2:H20"];
        r.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);

        Bitmap image = new Bitmap(Clipboard.GetImage());
        image.Save(@"C:\SCRATCH\image.png");

        // charting code, replaced with the above 
               /* ChartObject chartObj = ws.ChartObjects().Add(r.Left, r.Top, r.Width, r.Height); 

                chartObj.Activate();
                Chart chart = chartObj.Chart;
                chart.Paste();
                chart.Export(@"C:\SCRATCH\image.JPG", "JPG");
                chartObj.Delete(); */

编辑:将所有错误检查和流控制留给您,但在尝试访问它的内容之前(至少)使用ContainsImage()类的Clipboard方法是明智的。 。

答案 2 :(得分:1)

VBA 可能会更容易:

Sub PictureSaver()
    Dim ch As Chart
    Charts.Add
    Set ch = ActiveChart
    Sheets("Sheet4").Select
    Range("A1:D4").Select
    Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
    ch.Select
    ch.Paste
    ch.Export Filename:="sample.jpg"
    Application.DisplayAlerts = False
        ch.Delete
    Application.DisplayAlerts = True
End Sub