如何从 C# 应用程序将图片插入到 Excel 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11716873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:56:41  来源:igfitidea点击:

How to insert a picture in to Excel from C# app?

c#excel

提问by Pomster

I am trying to insert a picture into Excel Spread Sheet using my C# application.

我正在尝试使用我的 C# 应用程序将图片插入 Excel 电子表格。

I have used the following as my source. http://csharp.net-informations.com/excel/csharp-insert-picture-excel.htm

我使用以下作为我的来源。http://csharp.net-informations.com/excel/csharp-insert-picture-excel.htm

This whole line is underlined in blue.

整条线用蓝色下划线标出。

 xlWorkSheet.Shapes.AddPicture("C:\pic.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45); 

My Code:

我的代码:

private void btnWriteSpreedSheet_Click(object sender, EventArgs e)
{
    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;

    xlApp = new Excel.ApplicationClass();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    //xlWorkSheet.SetBackgroundPicture("C:/Users/Shaun/Documents/Visual Studio 2010/Projects/TestXMLToEXCEL/TestXMLToEXCEL/bin/Debugpic.JPG"); //

    //add some text 
    xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
    xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File";

    xlWorkSheet.Shapes.AddPicture("C:\pic.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45); //C:\csharp-xl-picture.JPG

     xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();

    releaseObject(xlApp);
    releaseObject(xlWorkBook);
    releaseObject(xlWorkSheet);

    MessageBox.Show ("File created !");
}

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        MessageBox.Show("Unable to release the Object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}


Error messages:

错误信息:

The best overloaded method match for 'Microsoft.Office.Interop.Excel.Shapes.AddPicture(string, Microsoft.Office.Core.MsoTriState, Microsoft.Office.Core.MsoTriState, float, float, float, float)' has some invalid arguments

The type 'Microsoft.Office.Core.MsoTriState' is defined in an assembly that is not referenced. You must add a reference to assembly 'office, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'.

Argument 2: cannot convert from 'Microsoft.Office.Core.MsoTriState [c:\users\shaun\documents\visual studio 2010\Projects\TestXMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs]' to 'Microsoft.Office.Core.MsoTriState'

Argument 3: cannot convert from 'Microsoft.Office.Core.MsoTriState [c:\users\shaun\documents\visual studio 2010\Projects\TestXMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs]' to 'Microsoft.Office.Core.MsoTriState'

'Microsoft.Office.Interop.Excel.Shapes.AddPicture(string, Microsoft.Office.Core.MsoTriState, Microsoft.Office.Core.MsoTriState, float, float, float, float)' 的最佳重载方法匹配有一些无效参数

“Microsoft.Office.Core.MsoTriState”类型是在未引用的程序集中定义的。您必须添加对程序集“office, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”的引用。

参数 2:无法从“Microsoft.Office.Core.MsoTriState [c:\users\shaun\documents\visual studio 2010\Projects\TestXMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs]”转换为“Microsoft.Office.Core.MsoTriState”

参数 3:无法从“Microsoft.Office.Core.MsoTriState [c:\users\shaun\documents\visual studio 2010\Projects\TestXMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs]”转换为“Microsoft.Office.Core.MsoTriState”



My References:

我的参考资料:

using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Microsoft.Office;
using System.Xml;

采纳答案by JMK

Add the following references:

添加以下引用:

  • Microsoft.Office.Interop.Excelfrom the .Net tab
  • Microsoft Office 14.0 Object Libraryfrom the COM tab
  • Microsoft.Office.Interop.Excel从 .Net 选项卡
  • Microsoft Office 14.0 Object Library从 COM 选项卡

Add the following using statements:

添加以下 using 语句:

using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

And then here is your method (slightly altered):

然后这是您的方法(略有改动):

private void BtnWriteSpreedSheetClick(object sender, EventArgs e)
{
    var xlApp = new Excel.Application();
    Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
    Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];

    xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
    xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File";

    xlWorkSheet.Shapes.AddPicture(@"C:\pic.JPG", MsoTriState.msoFalse, MsoTriState.msoCTrue, 50, 50, 300, 45);

    xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal);
    xlWorkBook.Close(true);
    xlApp.Quit();

    Marshal.ReleaseComObject(xlApp);

    MessageBox.Show("File created !");
}

回答by Pomster

You need to add the Microsoft excel library.

您需要添加 Microsoft excel 库。

enter image description here

在此处输入图片说明

回答by writeToBhuwan

Just add

只需添加

using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;

to your code and rebuild your solution before your run again.

到您的代码并在再次运行之前重建您的解决方案。

回答by Kitemark76

I am using this code with Microsoft.Office.Interop.Excel v 14.0:

我将此代码与 Microsoft.Office.Interop.Excel v 14.0 一起使用:

xlWorksheet.Shapes.AddPicture(@"c:\pics\logosmall.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 0, 0, 185, 42);

And have got images (jpgand png) in my excel sheets.

并且在我的 excel 表中有图像(jpgpng)。

回答by Stewart_R

As an alternative you could use one of the Open Xml libraries such as EPPlusto do this.

作为替代方案,您可以使用 Open Xml 库之一(例如EPPlus)来执行此操作。

In my opinion, EPPlus is much easier & more intuative than Excel interop with no need to manually release resources. It also has the added benefit that it can be performed on a machine without Excel installed.

在我看来,EPPlus 比 Excel 互操作更容易和更直观,无需手动释放资源。它还有一个额外的好处,它可以在没有安装 Excel 的机器上执行。

Something as simple as this with EPPlus works well:

像这样简单的 EPPlus 效果很好:

using (var excel = new ExcelPackage())
{
    var wks = excel.Workbook.Worksheets.Add("Sheet1");
    wks.Cells[1, 1].Value = "Adding picture below:";
    var pic = wks.Drawings.AddPicture("MyPhoto", new FileInfo("image.png"));
    pic.SetPosition(2, 0, 1, 0);
    excel.SaveAs(new FileInfo("outputfile.xlsx"));
}

回答by Robert Karamagi

    private void Button1_Click(object sender, EventArgs e)
    {

        Microsoft.Office.Interop.Excel._Application application = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = application.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

        SaveFileDialog saveDialog = new SaveFileDialog();
        saveDialog.FileName = "ImageToExcel.xlsx";
        if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            try
            {
                worksheet = workbook.ActiveSheet;
                worksheet.Name = "Image to Excel";
                string imageNetworkLocation = "\\192.168.240.110\images\image.png";
                worksheet.Shapes.AddPicture(imageNetworkLocation, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 0, 0, 170, 85);
                workbook.SaveAs(saveDialog.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                application.Quit();
                workbook = null;
                application = null;

            }
        }

        else
            try
            {
                workbook.Close(0);
                application.Quit();
                workbook = null;
                application = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
            }
            catch (System.Exception ex) 
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
    }