2009年4月21日 星期二

操作word檔案(三) - 開啟舊擋(Template)並修改後另存新檔

object filename = Server.MapPath("WordTemplate") + "\\" + "Template.doc" ; //開啟路徑
object readOnly = false;
object isVisible = true;
Object Nothing = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Word.ApplicationClass oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();

Microsoft.Office.Interop.Word.Document oWordDoc = oWordApp.Documents.Open(ref filename, ref Nothing,ref readOnly,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref isVisible,ref Nothing,ref Nothing,ref Nothing,ref Nothing);

oWordDoc.Activate();

IEnumerator ie = oWordDoc.Bookmarks.GetEnumerator() ;
while(ie.MoveNext())
{
Microsoft.Office.Interop.Word.Bookmark bm = (Microsoft.Office.Interop.Word.Bookmark)ie.Current ;
if(bm.Name == "BookMark1"){bm.Range.Text = "MicrosoftWord2003 第一行文字";}
else if(bm.Name == "BookMark2"){bm.Range.Text = "MicrosoftWord2003 第二行文字";}
else if(bm.Name == "BookMark3") //插入圖片.
{
object range = bm.Range ;
string picname = "c:\\Test\\test.gif" ; //http://localhost/WebTest/image001.jpg
Microsoft.Office.Interop.Word.InlineShape ins = oWordApp.Selection.InlineShapes.AddPictureBullet(picname,ref range);
ins.Width = 30 ;
ins.Height = 40 ;
}
else{}
}

//另存新檔
object savefilename = Server.MapPath("ExportDoc") + "\\" + "BookMark.doc" ; //存檔路徑
oWordDoc.SaveAs(ref savefilename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);

oWordApp.Application.Quit(ref Nothing, ref Nothing, ref Nothing);

this.Label3.Text = "< a href ='ExportDoc/"+ "BookMark.doc" +"'> 查看產生的文件 </a> ";

沒有留言:

張貼留言