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

13

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

我已经使用以下网址作为我的源代码。http://csharp.net-informations.com/excel/csharp-insert-picture-excel.htm

整个行都用蓝色下划线标出。

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

我的代码:

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();
    }
}
错误信息:

最佳重载方法匹配为'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 studio2010\Projects\TestXMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs]”转换为“Microsoft.Office.Core.MsoTriState”

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

我的参考文献:

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

只需添加对 Microsoft.Office.Core.dll 的引用即可。错误明确指出:类型 'Microsoft.Office.Core.MsoTriState' 在未被引用的程序集中定义。 - Renatas M.
你好像引用了一个版本,但是它使用的是不同的版本。你是否已经添加了对v.12 dll的引用? - Renatas M.
不是这样的,我似乎正在引用 interop.Microsoft.Office.Core.dll,它的版本是2.4.0.0。我应该在哪里找到最新版本的 v.12 Microsoft.Office.Core? - Pomster
7个回答

21

添加以下引用:

  • .Net选项卡中的Microsoft.Office.Interop.Excel
  • COM选项卡中的Microsoft Office 14.0 Object Library

添加以下using语句:

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

这里是您的方法(稍作修改):

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 !");
}

1
在我的应用程序中,图像插入是一个瓶颈。每个生成的XLSX文件至少有300-400个图像。当前的解决方案会调用worksheet.Shapes.AddPicture()方法多次来添加每张图片。这样非常缓慢。有没有什么变通方法可以让它更快? - mr_esp
可以将互联网上的位置作为AddPicture()的第一个参数,而不是本地文件吗?例如:"http://www.bla.com/someImage.png"? - B. Clay Shannon-B. Crow Raven

2
作为替代方案,您可以使用 Open Xml 库之一,例如 EPPlus 来完成此操作。
在我看来,EPPlus 比 Excel 互操作性更容易使用和更直观,而且无需手动释放资源。它还有一个额外的好处,即可以在没有安装 Excel 的计算机上执行。
使用 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"));
}

2

您需要添加微软Excel库。

输入图像描述


尽管你的回答已经四年了,但你比我领先两个版本;我只有 MS Excel 12.0 对象库的版本 1.60 可用。好吧,我还有 Excel 5.0,版本 1。 - B. Clay Shannon-B. Crow Raven
好吧,那没什么帮助——我本来需要它来使用MS.Office.Core,但是后来收到了922个构建错误消息。所以我把它移除了,并恢复到了我已经有的东西。 - B. Clay Shannon-B. Crow Raven

1

我正在使用 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);

我在我的Excel表格中有图片(jpgpng格式)。


1

只需添加

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

在再次运行之前,请返回您的代码并重新构建您的解决方案。


0
如果您想从资源中向Excel表格添加图像,可以使用以下代码(来自此答案):https://stackoverflow.com/a/16979892/8712569
    internal static void GenerateExcel()
    {
        Application excel;
        Workbook excelworkBook;
        Worksheet excelSheet;

        // Start Excel and get Application object.  
        excel = new Application();
        // for making Excel visible  
        excel.Visible = false;
        excel.DisplayAlerts = false;
        // Creating a new Workbook  
        excelworkBook = excel.Workbooks.Add(Type.Missing);
        // Get the active sheet  
        excelSheet = (Worksheet)excelworkBook.ActiveSheet;
        excelSheet.Name = "SheetWithImage";

        System.Drawing.Bitmap pic = Properties.Resources.my_logo;
        System.Windows.Forms.Clipboard.SetImage(pic);
        Range position = (Range)excelSheet.Cells[2, 2];
        excelSheet.Paste(position); //copy the clipboard to the given position

        excelworkBook.SaveAs("MyExcelFile.xlsx", XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
            false, false, XlSaveAsAccessMode.xlNoChange,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        excelworkBook.Close();
        excel.Quit();
    }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接