摘要:Excel 匯入圖檔
/// 將Canvas轉存成圖片檔
public System.Drawing.Image ExportingToImage(Canvas canvas, string sFile)
{
GlobalFunction.ExportingToPNG(sFile, canvas);
//將Canvas轉成byte[]
byte[] bytes = File.ReadAllBytes(sFile);
//在透過MemoryStream物件轉成System.Drawing.Image物件
MemoryStream ms = new MemoryStream(bytes);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
ms.Close();
return img;
}
// 將Canvas轉成至PNG檔
public static void ExportingToPNG(string sPath, Canvas canvas)
{
if (canvas == null) return;
//建立起點陣圖轉換物件
RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
(int)canvas.Width,
(int)canvas.Height,
100d,
100d,
PixelFormats.Pbgra32);
//制定被轉換的物件
renderBitmap.Render(canvas);
//建立串流
using (FileStream fs = new FileStream(sPath, FileMode.Create))
{
//建立PNG編碼器
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
//點陣圖編碼透過串流存成檔案
encoder.Save(fs);
}
}
//主程式
int x = 1, y = 10;
//取得Temp檔路徑
string sFile = System.IO.Path.GetTempFileName();
//將Canvas及剛取得的Temp路徑傳入,將會將Canvas傳回Image
System.Drawing.Image img = this.ExportingToImage(Route.CanvasGround, sFile);
//取得一個Range,來制定Insert Image to Excel的位置
Microsoft.Office.Interop.Excel.Range rangeTemp = ws.get_Range((Microsoft.Office.Interop.Excel.Range)ws.Cells[x, y], (Microsoft.Office.Interop.Excel.Range)ws.Cells[x, y]);
float PicLeft, PicTop;
//設定圖片放置的座標點
PicLeft = Convert.ToSingle(rangeTemp.Left) + 2;
PicTop = Convert.ToSingle(rangeTemp.Top) + 1;
System.Windows.Forms.Clipboard.SetDataObject(img, true);
//取得該Sheet Pictures的集合物件
Pictures pics = (Pictures)ws.Pictures(misValue);
//將Image Insert to 到 Pictures 集合中, 並回傳該Image的Picture物件
Picture pic = pics.Insert(sFile, misValue);
//設定Picture的座標及大小
pic.Top = PicTop;
pic.Left = PicLeft;
pic.Width = img.Width * 6 / 10;
pic.Height = img.Height * 6 / 10;