C#/VB.NET: Replace a Picture in Excel

Sometimes after you have finished an Excel workbook, you may need to replace some of the existing pictures with better ones for the purpose of making the workbook more appealing and persuasive. In this tutorial, you will learn how to replace a picture in Excel using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

  • Package Manager
PM> Install-Package Spire.XLS

Replace a Picture in Excel

The following are the detailed steps to replace a picture with another one using Spire.XLS for .NET.

  • C#
  • VB.NET
using Spire.Xls;
using Spire.Xls.Collections;
using System.Drawing;

namespace ReplacePictureinExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance 
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile (“Input.xls”);

            //Get the first sheet
            Worksheet sheet = workbook.Worksheets[0];

            //Get Excel picture collection
            PicturesCollection pictureCollection = sheet.Pictures;

            //Get the first picture from the collection 
            ExcelPicture excelPicture = pictureCollection[0];
            
            // Creates an Image from the specified file.
            excelPicture.Picture = Image.FromFile (image);

            //Save the document
            workbook.SaveToFile("ReplaceImage.xlsx", ExcelVersion.Version2013);
        }
    } 
}
Imports Spire.Xls
Imports Spire.Xls.Collections
Imports System.Drawing

Namespace ReplacePictureinExcel
	Class Program
		Private Shared Sub Main(args As String())

			'Create a Workbook instance 
			Dim workbook As New Workbook()
			'Load the Excel file
			workbook.LoadFromFile(Input.xls)

			'Get the first sheet
			Dim sheet As Worksheet = workbook.Worksheets(0)

			'Get Excel picture collection
			Dim pictureCollection As PicturesCollection = sheet.Pictures

			'Get the first picture from the collection 
			Dim excelPicture As ExcelPicture = pictureCollection(0)

			' Creates an Image from the specified file.
			excelPicture.Picture = Image.FromFile(image)

			'Save the document
			workbook.SaveToFile("ReplaceImage.xlsx", ExcelVersion.Version2013)
		End Sub
	End Class
End Namespace

The original file:

C#/VB.NET: Replace a Picture in Excel

The generated file:

C#/VB.NET: Replace a Picture in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.