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

Questions:

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

Image img = Image.FromFile("test.jpg");
sheet.get_Range("A1").set_Item(1,1,img);

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?
[WinForm]

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

Answer:

    System.Data.SqlClient.SqlDataReader rdr = null;
            System.Data.SqlClient.SqlConnection conn = null;
            System.Data.SqlClient.SqlCommand selcmd = null;
            try
            {
              conn = new System.Data.SqlClient.SqlConnection
            (System.Configuration.ConfigurationManager.ConnectionStrings
            ["ConnectionString"].ConnectionString);
//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);
              conn.Open();
              rdr = selcmd.ExecuteReader();
              while (rdr.Read())
              {
                byte[] YourImagebytearray = ((byte[])rdr["pic1"]);
                MemoryStream stream = new MemoryStream(bytes);
                var newImage = System.Drawing.Image.FromStream(stream);
                stream.Dispose();
              }
              if (rdr != null)
                rdr.Close();
            }
            finally
            {
              if (conn != null)
                  conn.Close();
            }