将图像插入Excel工作表不起作用

时间:2012-08-25 14:44:40

标签: c# winforms image excel insert

我正在尝试将图像插入excel表格,如下所示。

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

但是当excel在A1单元格中打开时,没有任何图片,
但只有这个结果: System.Drawing.Bitmap
那么问题是什么,我该如何解决呢。 第二个问题是:
如果我的图片位于数据库中,如何插入excel。我不想将它们保存到计算机以插入Excel? [WinForm的]

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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