需要添加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; }}