How to insert an image into a document with C# and .NET

Working with Excel data is an integral part of many people's professional activities, whether it's analyzing data, preparing reports, or creating presentation materials. Sometimes, to enhance the visual perception of information, it is necessary to insert images such as logos, graphics, or photographs. In this article, we'll look at how to use the SautinSoft.Excel library can easily and quickly insert images into Excel documents using C# and .NET.

The advantages should be highlighted:

  • Improve visual perception. Inserting images makes your documents more attractive and easier to read. Pictures can help visually highlight important points or illustrate data.
  • Branding. It is important for companies to maintain their corporate identity, and inserting a logo into charts or reports helps establish a corporate image.
  • Demonstration of the data. Images, such as charts or graphs, allow you to present data more clearly, which is especially useful when creating presentations or reports.
  • Simplification of information perception. People perceive and remember information presented in a visual format better than text. Thus, images can significantly improve the understanding of the presented data.
  • Step-by-step guide:

    1. Add SautinSoft.Excel from Nuget.
    2. Create a new Excel document and add a worksheet.
    3. Insert an image.
    4. Save the document.

    Полный код

    using SautinSoft.Excel;
    using System.IO;
    using SkiaSharp;
    
    namespace Example
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Get your free key here:   
                // https://sautinsoft.com/start-for-free/
    
                InsertImage();
                //InsertImageFromStream();
                //InsertImageWithAnchorCells();
                //InsertImageFromStreamWithAnchorCells();
            }
    
            /// <summary>
            /// Create xlsx file with an image inside.
            /// </summary>
    		/// <remarks>
            /// Details: https://sautinsoft.com/products/excel/help/net/developer-guide/insert-images-in-excel-csharp-vb.php
            /// </remarks>
            static void InsertImage()
            {
                string image = @"..\..\..\cup.jpg";
                string outFile = @"..\..\..\Result.xlsx";
    
                ExcelDocument excelDocument = new ExcelDocument();
    
                excelDocument.Worksheets.Add("Page 1");
                var worksheet = excelDocument.Worksheets["Page 1"];
    
                // Insert an image
                worksheet.Pictures.Add(image, SKRect.Create(1080, 960));
    
                excelDocument.Save(outFile);
    
                // Important for Linux: Install MS Fonts
                // sudo apt install ttf-mscorefonts-installer -y
    
                // Open the result for demonstration purposes.
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
            }
    
            static void InsertImageFromStream()
            {
                string image = @"..\..\..\cup.jpg";
                string outFile = @"..\..\..\Excel Image.xlsx";
    
                ExcelDocument excelDocument = new ExcelDocument();
    
                excelDocument.Worksheets.Add("Page 1");
                var worksheet = excelDocument.Worksheets["Page 1"];
    
                // Insert an image from a stream
                byte[] imageInBytes = File.ReadAllBytes(image);
                using (var streamImage = new MemoryStream(imageInBytes))
                {
                    worksheet.Pictures.Add(streamImage, SKRect.Create(1080, 960), ExcelPictureFormat.Jpeg);
                    excelDocument.Save(outFile);
                }
    
                // Important for Linux: Install MS Fonts
                // sudo apt install ttf-mscorefonts-installer -y
    
                // Open the result for demonstration purposes.
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
            }
    
            static void InsertImageWithAnchorCells()
            {
                string image = @"..\..\..\cup.jpg";
                string outFile = @"..\..\..\Excel Image.xlsx";
    
                ExcelDocument excelDocument = new ExcelDocument();
    
                excelDocument.Worksheets.Add("Page 1");
                var worksheet = excelDocument.Worksheets["Page 1"];
    
                // Insert an image anchored to cells
                worksheet.Pictures.Add(image, PositionOption.FreeFloating, new AnchorCell(worksheet.Columns[6], worksheet.Rows[6], true),
                    new AnchorCell(worksheet.Columns[20], worksheet.Rows[40], true));
                excelDocument.Save(outFile);
    
                // Important for Linux: Install MS Fonts
                // sudo apt install ttf-mscorefonts-installer -y
    
                // Open the result for demonstration purposes.
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
            }
    
            static void InsertImageFromStreamWithAnchorCells()
            {
                string image = @"..\..\..\cup.jpg";
                string outFile = @"..\..\..\Excel Image.xlsx";
    
                ExcelDocument excelDocument = new ExcelDocument();
    
                excelDocument.Worksheets.Add("Page 1");
                var worksheet = excelDocument.Worksheets["Page 1"];
    
                // Insert an image from a stream, anchored to cells
                byte[] imageInBytes = File.ReadAllBytes(image);
                using (var streamImage = new MemoryStream(imageInBytes))
                {
                    worksheet.Pictures.Add(streamImage, PositionOption.MoveAndSize, new AnchorCell(worksheet.Columns[6], worksheet.Rows[6], true),
                        new AnchorCell(worksheet.Columns[20], worksheet.Rows[40], true), ExcelPictureFormat.Jpeg);
                    excelDocument.Save(outFile);
                }
    
    
                // Important for Linux: Install MS Fonts
                // sudo apt install ttf-mscorefonts-installer -y
    
                // Open the result for demonstration purposes.
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
            }
        }
    }

    Download

    Option Infer On
    
    Imports SautinSoft.Excel
    Imports System.IO
    Imports SkiaSharp
    
    Namespace Example
    	Friend Class Program
    		Shared Sub Main(ByVal args() As String)
    			' Get your free key here:   
    			' https://sautinsoft.com/start-for-free/
    
    			InsertImage()
    			'InsertImageFromStream();
    			'InsertImageWithAnchorCells();
    			'InsertImageFromStreamWithAnchorCells();
    		End Sub
    
    		''' <summary>
    		''' Create xlsx file with an image inside.
    		''' </summary>
    		''' <remarks>
    		''' Details: https://sautinsoft.com/products/excel/help/net/developer-guide/insert-images-in-excel-csharp-vb.php
    		''' </remarks>
    		Private Shared Sub InsertImage()
    			Dim image As String = "..\..\..\cup.jpg"
    			Dim outFile As String = "..\..\..\Result.xlsx"
    
    			Dim excelDocument As New ExcelDocument()
    
    			excelDocument.Worksheets.Add("Page 1")
    			Dim worksheet = excelDocument.Worksheets("Page 1")
    
    			' Insert an image
    			worksheet.Pictures.Add(image, SKRect.Create(1080, 960))
    
    			excelDocument.Save(outFile)
    
    			' Important for Linux: Install MS Fonts
    			' sudo apt install ttf-mscorefonts-installer -y
    
    			' Open the result for demonstration purposes.
    			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
    		End Sub
    
    		Private Shared Sub InsertImageFromStream()
    			Dim image As String = "..\..\..\cup.jpg"
    			Dim outFile As String = "..\..\..\Excel Image.xlsx"
    
    			Dim excelDocument As New ExcelDocument()
    
    			excelDocument.Worksheets.Add("Page 1")
    			Dim worksheet = excelDocument.Worksheets("Page 1")
    
    			' Insert an image from a stream
    			Dim imageInBytes() As Byte = File.ReadAllBytes(image)
    			Using streamImage = New MemoryStream(imageInBytes)
    				worksheet.Pictures.Add(streamImage, SKRect.Create(1080, 960), ExcelPictureFormat.Jpeg)
    				excelDocument.Save(outFile)
    			End Using
    
    			' Important for Linux: Install MS Fonts
    			' sudo apt install ttf-mscorefonts-installer -y
    
    			' Open the result for demonstration purposes.
    			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
    		End Sub
    
    		Private Shared Sub InsertImageWithAnchorCells()
    			Dim image As String = "..\..\..\cup.jpg"
    			Dim outFile As String = "..\..\..\Excel Image.xlsx"
    
    			Dim excelDocument As New ExcelDocument()
    
    			excelDocument.Worksheets.Add("Page 1")
    			Dim worksheet = excelDocument.Worksheets("Page 1")
    
    			' Insert an image anchored to cells
    			worksheet.Pictures.Add(image, PositionOption.FreeFloating, New AnchorCell(worksheet.Columns(6), worksheet.Rows(6), True), New AnchorCell(worksheet.Columns(20), worksheet.Rows(40), True))
    			excelDocument.Save(outFile)
    
    			' Important for Linux: Install MS Fonts
    			' sudo apt install ttf-mscorefonts-installer -y
    
    			' Open the result for demonstration purposes.
    			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
    		End Sub
    
    		Private Shared Sub InsertImageFromStreamWithAnchorCells()
    			Dim image As String = "..\..\..\cup.jpg"
    			Dim outFile As String = "..\..\..\Excel Image.xlsx"
    
    			Dim excelDocument As New ExcelDocument()
    
    			excelDocument.Worksheets.Add("Page 1")
    			Dim worksheet = excelDocument.Worksheets("Page 1")
    
    			' Insert an image from a stream, anchored to cells
    			Dim imageInBytes() As Byte = File.ReadAllBytes(image)
    			Using streamImage = New MemoryStream(imageInBytes)
    				worksheet.Pictures.Add(streamImage, PositionOption.MoveAndSize, New AnchorCell(worksheet.Columns(6), worksheet.Rows(6), True), New AnchorCell(worksheet.Columns(20), worksheet.Rows(40), True), ExcelPictureFormat.Jpeg)
    				excelDocument.Save(outFile)
    			End Using
    
    
    			' Important for Linux: Install MS Fonts
    			' sudo apt install ttf-mscorefonts-installer -y
    
    			' Open the result for demonstration purposes.
    			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
    		End Sub
    	End Class
    End Namespace
    

    Download


    Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



    Вопросы и предложения всегда приветствуются!

    Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.