Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将excel工作表导出为图像?_C#_Excel - Fatal编程技术网

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

C# 如何将excel工作表导出为图像?,c#,excel,C#,Excel,我正在尝试从excel工作表生成图像。经过大量研究后,我使用了以下代码,但在某些情况下,我得到了一个例外: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Excel; namespace ConsoleApplication1 { class Prueba { [STAThre

我正在尝试从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。

在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

这对我在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();
        }



    }
}

对于控制台应用程序,您还需要看到:

无需创建
图表
对象。在
范围内调用
CopyPicture()
,将图像放入系统剪贴板。如果需要,您只需两步即可完成:

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

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

你得到了什么异常?在哪一行?在注释行的下面,我得到了注释所说的内容为什么不直接从剪贴板导出图像?好主意。已经尝试过,问题是剪贴板.GetDataObject()不会返回任何内容,即使我可以将其粘贴到MS Paint中。我可以使用VBA standalone吗?我问这个问题是因为我需要做更多的事情,比如查询数据库和其他操作这是一个很好的问题!可能会修改脚本,使其在工作簿的“外部”运行…………我会打开一个新帖子来问这个问题……您的答案是可以的。但出于某种原因,我得到了一个例外。我提出了一个新问题来解决这个问题:注意,您不需要使用剪贴板——您只需将工作簿强制转换为IDataObject,并获取所选工作表的位图格式即可。此外,Jpeg对于Excel屏幕帽来说是一个可怕的选择(该格式针对摄影进行了优化,对于这样的目的,Jpeg将引入视觉伪影)——将图像编码为PNG。我尝试将您的代码用于我的控制台应用程序,但“Clipboard.GetDataObject()”的值为空。您能给我一些建议吗?与上面的注释相同--不需要覆盖剪贴板--直接将工作簿对象强制转换为IDataObject--这很有效。