Image are not added to the document

Hello everyone,

I need to add an image to a .xlsx file.
An image in .png format with a size of 150x150 pixels
I tried several methods, but without success:

Method 1. According to the published documentation here

Moreover, using the link at the bottom of the page in the Download Running Code section - I downloaded an example from github, which should be a working version
https://github.com/aspose-cells/Aspose.Cells-for-.NET/releases/download/Aspose.Cells_Vs_NPOI_HWPF_and_XWPF_v1.2/Add.Image.in.Worksheet.zip

But after unzipping this example, it turned out that no image was added. I am attaching the file generated as a result of executing the downloaded example in Method1_ResultFile.xlsx file inside attached zip archive

Method 2. Change the cell size so that it can be inserted into the image
I tried to fix the code myself so that the cell size matches the image size (150x150) but also without success.

const string imagePath =
                @"C:\Users\User\Documents\logo.png";
            const string outputFilePath =
                @"C:\Users\User\Documents\Method2_ResultFile.xlsx";
            Workbook workbook = new Workbook();
            WorksheetCollection worksheets = workbook.Worksheets;
            Worksheet worksheet = worksheets.Add("My Worksheet");
            worksheet.Cells["C2"].Value = "Image";
            worksheet.Cells.SetRowHeight(3, 150);
            worksheet.Cells.SetColumnWidth(2, 150);
            int index = worksheet.Pictures.Add(3, 2, 3, 2, imagePath);
            Picture pic = worksheet.Pictures[index];
            pic.Placement = PlacementType.FreeFloating;
            workbook.Save(outputFilePath);

I am attaching the file generated as a result of executing Method 2 as Method2_ResultFile.xlsx file inside attached zip archive

Method 3. Via SetHeaderPicture
According to the code posted here

I was unable to add an image to the file

private void PrintQrImageToExcelFile(string documentFilePath)
        {
            const string imagePath =
                @"C:\Users\User\Documents\logo.png";

            if (!File.Exists(documentFilePath))
                throw new FileNotFoundException("File not found", documentFilePath);
            
            FileStream inFile;
            byte[] binaryData;
            inFile = new System.IO.FileStream(imagePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            binaryData = new Byte[inFile.Length];
            long bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length);
            var workbook = new Workbook(documentFilePath);
            foreach (Worksheet worksheet in workbook.Worksheets)
            {
                PageSetup pageSetup = worksheet.PageSetup;
                pageSetup.SetHeaderPicture(1, binaryData);
                pageSetup.SetHeader(1, "&G");
                pageSetup.SetHeader(2, "&A");
            }

            const string outputFilePath = @"C:\Users\User\Documents\Method3_ResultFile.xlsx";
            workbook.Save(outputFilePath);
            inFile.Close(); 
        }

Only this method works fine - but once you open file you are not able to see the image until you select “File → Print” menu to see the file in print preview mode
I am attaching the file generated as a result of executing Method 3 as Method3_ResultFile.xlsx file inside attached zip archive

Method 4. Via SetPicture
Below is the code:

private void PrintQrImageToExcelFileMethod4(string documentFilePath)
        {
            const string imagePath =
                @"C:\Users\User\Documents\logo.png";
            const string imageScript = "&G";

            if (!File.Exists(documentFilePath))
                throw new FileNotFoundException("File not found", documentFilePath);

            if (string.IsNullOrWhiteSpace(imagePath) && !File.Exists(imagePath))
                throw new FileNotFoundException("QR image path not found", nameof(imagePath));
            
            var qrImageBytes = File.ReadAllBytes(imagePath);
            
            Program.SetLicenseExcel();
            
            var workbook = new Workbook(documentFilePath);
            foreach (Worksheet worksheet in workbook.Worksheets)
            {
                worksheet.PageSetup.SetPicture(
                    isFirst: true,
                    isEven: true,
                    isHeader: true,
                    section: 0,
                    qrImageBytes);
                worksheet.PageSetup.SetFirstPageHeader(section: 0, imageScript);
            }
            
            const string outputFilePath = @"C:\Users\User\Documents\Method4_ResultFile.xlsx";
            workbook.Save(outputFilePath);
        }

I am attaching the file generated as a result of executing Method 4 as Method4_ResultFile.xlsx file inside attached zip archive

Input file will be found as ExcelSample_TEST.xlsx inside attached zip archive

Please provide a working examples with explanations and comments, as a result of which I would be able to add an image in .png format with a size of 150x150 pixels to an existing .xlsx document and the image could be seen once file was open

Thank you
Aspose.zip (283.9 KB)

@tolmachovvs

To add an image to an existing .xlsx document using Aspose.Cells, you can use the following code snippet. This example demonstrates how to insert a PNG image into a specific cell in the worksheet, ensuring that the image is visible when the file is opened.

Here’s a working example:

using Aspose.Cells;
using System.IO;

class Program
{
    static void Main()
    {
        const string imagePath = @"C:\Users\User\Documents\logo.png";
        const string inputFilePath = @"C:\Users\User\Documents\ExcelSample_TEST.xlsx";
        const string outputFilePath = @"C:\Users\User\Documents\ResultFile.xlsx";

        // Load the existing workbook
        Workbook workbook = new Workbook(inputFilePath);
        Worksheet worksheet = workbook.Worksheets[0]; // Access the first worksheet

        // Set the row height and column width to match the image size
        worksheet.Cells.SetRowHeight(2, 150); // Row index is 2 for C2
        worksheet.Cells.SetColumnWidth(2, 20); // Column index is 2 for C

        // Add the image to the worksheet
        int pictureIndex = worksheet.Pictures.Add(2, 2, imagePath); // Add image at C2
        Picture picture = worksheet.Pictures[pictureIndex];
        picture.Placement = PlacementType.MoveAndSize; // Ensure the image moves and resizes with cells

        // Save the workbook
        workbook.Save(outputFilePath);
    }
}

Explanation:

  1. Load the Workbook: The existing Excel file is loaded into a Workbook object.
  2. Set Row Height and Column Width: The row height and column width are adjusted to accommodate the image size (150 pixels in height).
  3. Add the Image: The image is added to the specified cell (C2) using the Add method of the Pictures collection.
  4. Placement Type: The placement type is set to MoveAndSize, ensuring that the image will be visible and will adjust if the cell size changes.
  5. Save the Workbook: Finally, the modified workbook is saved to a new file.

Ensure that the image path and input file path are correct. This code should successfully add the image to your Excel file, and it will be visible when you open the file.

1 Like

@tolmachovvs,

Thanks for the sample files, code snippets and details.

First of all, your issue arises from the way you are utilizing the PictureCollection.Add() method in the following line of code.:

int index = worksheet.Pictures.Add(3, 2, 3, 2, imagePath);

Here, you are setting lower right row (3rd parameter) to “3” and lower right column (4th parameter) to “2” which will surely squeeze the image and it won’t be displayed with bare eyes in the Excel worksheet until you select the picture in “Selection pane” menu option (window). See the screen shot for your reference, I used one of your output Excel file here.
scshot.png (52.6 KB)
Obviously, there is a slight mistake in the line of code of the document (which you followed). We are sorry for that and we will correct it in the document soon. To quickly correct it, you should give right/valid values to the third and fourth parameter for the method accordingly.

To make you understand precisely on how you can add pictures with its original size or customized size, please see the following examples in the following three tests (I have also added a few comments for your reference):

//Test1
const string imagePath = "e:\\test2\\Aspose\\logo.png";
const string outputFilePath = "e:\\test2\\outTest1.xlsx";
Workbook workbook = new Workbook();
WorksheetCollection worksheets = workbook.Worksheets;
Worksheet worksheet = worksheets.Add("My Worksheet");
worksheet.Cells["C2"].Value = "Image";
worksheet.Cells.SetRowHeight(3, 150);//Extend 4th row height 150 points 
worksheet.Cells.SetColumnWidth(2, 150);//Set C column width 150 chars
//Insert picture to  fit into C4 cell
int index = worksheet.Pictures.Add(3, 2, 4, 3, imagePath);
Aspose.Cells.Drawing.Picture pic = worksheet.Pictures[index];
pic.Placement = PlacementType.FreeFloating;
workbook.Save(outputFilePath);
//Test2
const string imagePath = "e:\\test2\\Aspose\\logo.png";
const string outputFilePath = "e:\\test2\\outTest2.xlsx";
Workbook workbook = new Workbook();
WorksheetCollection worksheets = workbook.Worksheets;
Worksheet worksheet = worksheets.Add("My Worksheet");
worksheet.Cells["C2"].Value = "Image";
worksheet.Cells.SetRowHeightPixel(3, 150);//Extend 4th row height 150 pixels
worksheet.Cells.SetColumnWidthPixel(2, 150);//Set C column width 150 pixels
//Insert picture into C4 cell with its original size (150 * 150 pixels)
int index = worksheet.Pictures.Add(3, 2, imagePath);
Aspose.Cells.Drawing.Picture pic = worksheet.Pictures[index];
pic.Placement = PlacementType.FreeFloating;
workbook.Save(outputFilePath);
//Test3
const string imagePath = "e:\\test2\\Aspose\\logo.png";
const string outputFilePath = "e:\\test2\\outTest3.xlsx";
Workbook workbook = new Workbook();
WorksheetCollection worksheets = workbook.Worksheets;
Worksheet worksheet = worksheets.Add("My Worksheet");
worksheet.Cells["C2"].Value = "Image";
//Insert picture into C4 cell with its original size (150 * 150 pixels)
int index = worksheet.Pictures.Add(3, 2, imagePath);
Aspose.Cells.Drawing.Picture pic = worksheet.Pictures[index];
pic.Placement = PlacementType.FreeFloating;
workbook.Save(outputFilePath);

Please find attached the zipped archive containing the output Excel files.
Tests.zip (31.9 KB)

Additinally, we recommend you to kindly see and browse the document(s) with examples for your complete reference: Managing Pictures|Documentation

Hope, it helps and you understand now.

Let us know if we can be of any further help.

1 Like