Kuldip Rana
Kuldip Rana

Reputation: 131

Add Picture in Excel on Particular Cell with C#

I am trying to add an image into Excel cell at row 3 column 1 as specified below. The compiler gave me an error. Did I do something wrong here? Thanks in advance for your suggestions.

Excel.Application xlApp; 
Excel.Workbook wb; 
Excel.Worksheet ws; 
object misValue = System.Reflection.Missing.Value; 
xlApp = new Excel.Application(); 
wb = xlApp.Workbooks.Add(misValue); 
ws = (Excel.Worksheet)wb.Worksheets.get_Item(1); 
ws.Cells[3, 1] = ws.Shapes.AddPicture("C:\\photos\\4a.png", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 75, 75, 350, 50);

Upvotes: 2

Views: 31484

Answers (2)

shakeel
shakeel

Reputation: 1725

Aspose.Cells API can be used to add a picture in Excel on particular cell with C# or with other programming languages e.g. Java, C++ etc.

For demonstration, please see the following C# code and the Snapshot that shows the input Excel file and the output Excel file generated by Aspose.Cells API after the execution of the code. As you can see inside the snapshot, the cell C12 contains the picture.

Please also read the comments inside the code for more help.

C#

// Load input Excel file inside Aspose.Cells Workbook object.
Workbook wb = new Workbook("SampleAddPictureInExcelCell.xlsx");

// Access first worksheet.
Worksheet ws = wb.Worksheets[0];

// Access cell C12 by name.
Cell cell = ws.Cells["C12"];

// Add picture in Excel cell.
int idx = ws.Pictures.Add(cell.Row, cell.Column, "D:/Download/Penguins.jpg");

// Access the picture by index.
Picture pic = ws.Pictures[idx];

// Get the column width and row height of the cell in inches.
double w = ws.Cells.GetColumnWidthInch(cell.Column);
double h = ws.Cells.GetRowHeightInch(cell.Row);

// Adjust the picture width and height as per cell width and height.
pic.WidthInch = w;
pic.HeightInch = h;

// Save the workbook in output Excel file.
wb.Save("OutputAddPictureInExcelCell.xlsx", SaveFormat.Xlsx);

Snapshot showing the input Excel file and output Excel file generated by Aspose.Cells API. Here cell C12 contains the picture.

Snapshot showing the input Excel file and output Excel file generated by Aspose.Cells API. Here cell C12 contains the picture.

Upvotes: 0

Pranav Patel
Pranav Patel

Reputation: 1559

you have to add picture like following

Microsoft.Office.Interop.Excel.Range oRange = (Microsoft.Office.Interop.Excel.Range)ws.Cells[3, 1];
float Left = (float)((double)oRange.Left);
float Top = (float)((double)oRange.Top);
const float ImageSize = 32;
ws.Shapes.AddPicture("C:\\pic.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);

Upvotes: 9

Related Questions