2009年10月25日 星期日

Word 套表

上周為了寫Word 套表,花了很多時間去找尋解決方案。

其實之前就已經用過把Word 2003存成XML格式,然後用更新字串的方式解決Word簡單套表。

不過這次的需求是,要把圖片從資料庫讀出,塞到指定的儲存格上。



一開始想說不是每個使用者都有Word 2007,所以規劃就是使用Microsoft.Office.Interop.Word來插入圖片。

[範例] 使用bookmark,這種適用Word 2003。

開啟Word 範本,在要插入圖片位置上插入書簽,存檔,關閉。

在程式加入Microsoft.Office.Interop.Word 參考。

object oMissing = Type.Missing;

object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;

doc.Content.Collapse(ref oCollapseEnd);

string filename = @"c:\temp\WordMLImage.bmp";



//把圖片塞到Word

bookmarkName = "StuPhoto";

if (doc.Bookmarks.Exists(bookmarkName)) {

Object name = bookmarkName;

Microsoft.Office.Interop.Word.Range range = doc.Bookmarks.get_Item(ref name).Range;

range.InlineShapes.AddPicture(filename,ref oMissing, ref oMissing, ref oMissing);

}


//save file

object newFileName = @"C:\temp\changedFile.doc";

doc.SaveAs(ref newFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

_wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);

但這種方式只適合單機程式,因為看了一些文章後,發現這種方式在WEB 多人使用情況會造成鎖死與資源浪費的問題。

沒有留言:

張貼留言