C#实现使用Excel COM组件向Excel文件中添加图片的Demo
需要添加Microsoft.Office.Interop.Excel;及Microsoft.Office.Core;两个命名空间及对应的引用。
比如我Windows 7下装的Office 2007,是添加的是一个COM组件和一个.Net组件的引用,如下图:
而我公司的电脑添加的是Microsoft Excel Object Library 和Microsoft Object Library 。
代码如下:
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Reflection; using System.IO; using Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Excel.Application app = new Application(); app.Visible = false; app.DisplayAlerts = false; Workbook workBook = app.Workbooks.Open(Server.MapPath("test_ Excel.xls"), Missing.Value, Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); //设置为操作当前workBook的sheet1 Worksheet workSheet = (Worksheet)workBook.Worksheets[1]; string imgPath = Server.MapPath("test_Img.jpg"); byte[] bytesArr = PicToByteArr(imgPath); System.Drawing.Image bmp = ReturnPhoto(bytesArr);//图片数据 int x = 1; int y = 1; Range rangeTemp = workSheet.get_Range((Range)workSheet.Cells[x, y], (Range)workSheet.Cells[x, y]); //rangeTemp.Select(); float PicLeft, PicTop; PicLeft = Convert.ToSingle(rangeTemp.Left) + 2; PicTop = Convert.ToSingle(rangeTemp.Top) + 1; workSheet.Shapes.AddPicture(imgPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, bmp.Width * 8 / 10, bmp.Height * 8 / 10); workBook.Save(); workBook.Close(null, null, null); app.Workbooks.Close(); app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rangeTemp); System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } /// <summary> /// 将图片转换为字节数组 /// </summary> /// <param name="path">图片的路径</param> /// <returns>字节数组</returns> public byte[] PicToByteArr(string path) { FileStream fs = new FileStream(path, FileMode.Open);//将图片写入流中。 int filelength = 0; filelength = (int)fs.Length; //获得文件长度 Byte[] byteArr = new Byte[filelength]; //建立一个字节数组 fs.Read(byteArr, 0, filelength); //按字节流读取 fs.Close(); return byteArr; } /// <summary> /// 参数是byte返回图片 /// </summary> /// <param name="byteArr">字节数组</param> /// <returns>图片</returns> public System.Drawing.Image ReturnPhoto(byte[] byteArr) { MemoryStream ms = new MemoryStream(byteArr); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); ms.Close(); return img; } }