Insert image in Excel

  • NPOI
  • Spire.XLS
  • Download Sample Code

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NPOI
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load workbook
            IWorkbook workbook = new XSSFWorkbook(new FileStream("../../../Data/Sample.xlsx", FileMode.Open));

            //Get the first sheet
            ISheet sheet = workbook.GetSheetAt(0);

            //Add picture data to the workbook
            byte[] bytes = File.ReadAllBytes("../../../Data/image.jpg");
            workbook.AddPicture(bytes, PictureType.JPEG);

            //Add a picture shape and set its position
            IDrawing drawing = sheet.CreateDrawingPatriarch();
            IClientAnchor anchor = workbook.GetCreationHelper().CreateClientAnchor();
            anchor.Dx1 = 0;
            anchor.Dy1 = 0;
            anchor.Col1 = 9;
            anchor.Row1 = 10;
            IPicture picture = drawing.CreatePicture(anchor, 0);

            //Automatically adjust the image size
            picture.Resize();

            //Save the file
            FileStream file = File.Create("ExcelImage.xlsx");
            workbook.Write(file);
            file.Close();

            //Launch
            System.Diagnostics.Process.Start("ExcelImage.xlsx");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Xls;

namespace Spire.XLS
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create Workbook
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("../../../Data/Sample.xlsx");

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

            //Insert Image
            sheet.Pictures.Add(12, 10, "../../../Data/image.jpg");

            //Save and Launch
            workbook.SaveToFile("ExcelImage.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("ExcelImage.xlsx");

        }
    }
}