namco
namco

Reputation: 6338

inserting an image to excel sheet doesnt work

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]

Upvotes: 1

Views: 2998

Answers (2)

Hassan Boutougha
Hassan Boutougha

Reputation: 3929

    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();
            }

Upvotes: 1

Hassan Boutougha
Hassan Boutougha

Reputation: 3929

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

Upvotes: 2

Related Questions