In this article I will show you a simple code to past the image given on a path in an excel file sheet. Herer if excel file is not available on that case create the excel file and if sheet is not available on that case create the sheet and past it.
So first we will install the ClosedXML NuGet package.
Install-Package ClosedXML
After installing the CloseXML package use the below code to place the xml in a specific cell as a starting point. Herer code will not make any change in image size. It will past without making any change in image width and height.using ClosedXML.Excel;
using System;
using System.IO;
public static void InsertImageInExcel(
string excelFilePath,
string sheetName,
string startCellNo,
string imagePath)
{
// Validate input
if (string.IsNullOrWhiteSpace(excelFilePath))
throw new ArgumentException("Excel file path is required.");
if (string.IsNullOrWhiteSpace(sheetName))
throw new ArgumentException("Sheet name is required.");
if (string.IsNullOrWhiteSpace(startCellNo))
throw new ArgumentException("Start cell number is required.");
if (!File.Exists(imagePath))
throw new FileNotFoundException("Image file not found.", imagePath);
// Open existing Excel file or create a new one
using (var workbook = File.Exists(excelFilePath)
? new XLWorkbook(excelFilePath)
: new XLWorkbook())
{
// Get existing sheet or create a new sheet
var worksheet = workbook.Worksheets
.TryGetWorksheet(sheetName, out var existingSheet)
? existingSheet
: workbook.Worksheets.Add(sheetName);
// Get the starting cell
var cell = worksheet.Cell(startCellNo);
// Insert image at the cell position
var picture = worksheet.AddPicture(imagePath)
.MoveTo(cell);
// Keep the image's original dimensions
// Do not call WithSize() or FitToCell()
// Save the Excel file
workbook.SaveAs(excelFilePath);
}
}
In above code I have verified the sheet and does not exist on that case create it and get the starting cell as per passed string start cell value. After getting the start cell detail place the image by using AddPicture method. In this method passe the image path. If you want to past the specific size image you need to use the below code.
var picture = worksheet.AddPicture(imagePath)
.MoveTo(cell)
.WithSize(300, 200);
Now we have done lets run and check the output. check the final output as shown below.
