Home » excel » c# – inserting an image to excel sheet doesnt work

c# – inserting an image to excel sheet doesnt work

Posted by: admin May 14, 2020 Leave a comment


i’m trying to insert an image to excel sheet like below.

Image img = Image.FromFile("test.jpg");

but when excel opens in A1 cell there is not any picture,
but there is only this result:System.Drawing.Bitmap
So what is the problem, how can i solve it.
And Second Question is:
how to insert to excel if my pictures are located in database. and i dont want to save them to computer for inserting to the excel?

How to&Answers:
Try this:

object missing = System.Reflection.Missing.Value;
Excel.Range picPosition = sheet.get_Range("A1"); // retrieve the range for picture insert
Excel.Pictures p = yourWorksheet.Pictures(missing) as Excel.Pictures;
Excel.Picture pic = null;
pic = p.Insert(yourImageFilePath, missing);
pic.Left = Convert.ToDouble(picRange.Left);
pic.Top = picRange.Top;
pic.Placement = // Can be any of Excel.XlPlacement.XYZ value


    System.Data.SqlClient.SqlDataReader rdr = null;
            System.Data.SqlClient.SqlConnection conn = null;
            System.Data.SqlClient.SqlCommand selcmd = null;
              conn = new System.Data.SqlClient.SqlConnection
//here set your query to get image from databse
              selcmd = new System.Data.SqlClient.SqlCommand
            ("select pic1 from msg where msgid=" + 
            context.Request.QueryString["imgid"], conn);
              rdr = selcmd.ExecuteReader();
              while (rdr.Read())
                byte[] YourImagebytearray = ((byte[])rdr["pic1"]);
                MemoryStream stream = new MemoryStream(bytes);
                var newImage = System.Drawing.Image.FromStream(stream);
              if (rdr != null)
              if (conn != null)