简体   繁体   English

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

[英]How can I export an excel worksheet as image?

I'm triying to generate an image from an excel worksheet.我正在尝试从 excel 工作表生成图像。 After a lot of research, I'm using the following code, but at some point I get an exception:经过大量研究,我正在使用以下代码,但在某些时候出现异常:

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();                
            }

        }
    }
}

I'm using Office 2013, 64 bits, Windows 7 64 and.Net 4.5.我正在使用 Office 2013,64 位,Windows 7 64 和 .Net 4.5。

This worked for me in a WinForms project: 这在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();
        }



    }
}

For a console app you need to see also: http://blog.another-d-mention.ro/programming/c/use-clipboard-copypaste-in-c-console-application/ 对于控制台应用程序,您还需要查看: http//blog.another-d-mention.ro/programming/c/use-clipboard-copypaste-in-c-console-application/

No need to create a Chart object. 无需创建Chart对象。 Calling CopyPicture() on the Range puts the image on the system clipboard. Range上调用CopyPicture()会将图像放在系统剪贴板上。 You can finish it off in as little as two steps, if you want: 如果你愿意,你可以在两个步骤完成它:

        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(); */

EDIT: Leaving all the error checking and flow control to you, but it would be wise of course to (at least) use the ContainsImage() method of the Clipboard class before trying to access it's content. 编辑:将所有错误检查和流控制留给您,但在尝试访问它的内容之前(至少)使用Clipboard类的ContainsImage()方法是明智的。

Might be easier in VBA : 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
                    //station--> excel file path
                    var app = new Microsoft.Office.Interop.Excel.Application();
                    var xls = app.Workbooks.Open(Station,false,true);
                    Microsoft.Office.Interop.Excel.Sheets sheets = xls.Worksheets;
                    for (int j = 1; j <= sheets.Count; j++)
                    {
                        Microsoft.Office.Interop.Excel.Worksheet sheet = sheets[j];
                        string startRange = "A1";
                        Microsoft.Office.Interop.Excel.Range endRange = sheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
                        Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(startRange, endRange);
                        range.Rows.AutoFit();
                        range.Columns.AutoFit();
                        range.Copy();

                        BitmapSource image = Clipboard.GetImage();
                        FormatConvertedBitmap fcbitmap = new FormatConvertedBitmap(image, PixelFormats.Bgr32, null, 0);
                        using (var fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + j + ".jpg", FileMode.Create))
                        {
                            PngBitmapEncoder encoder = new PngBitmapEncoder();
                            encoder.Interlace = PngInterlaceOption.On;
                            encoder.Frames.Add(BitmapFrame.Create(fcbitmap));
                            encoder.Save(fileStream);
                        }
                        Set_Cavnas(AppDomain.CurrentDomain.BaseDirectory  +j + ".jpg");
                        File.Delete(AppDomain.CurrentDomain.BaseDirectory  +j + ".jpg");
                    }
                    //release resources
                    app.DisplayAlerts = false;
                    xls.Close(false);
                    app.Quit();
                    GC.Collect();

Just used it at work, you can see the results enter image description here enter image description here刚在工作中使用,可以看到效果 在此处输入图像描述 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM