2012-09-11 98 views
0

我正在嘗試使用Microsoft Office Interop創建Word文檔。該文件應包含一張圖片和一些表格內容。但是,當我添加內容時,它不會以我需要的方式添加。在C#中創建Word文檔#

我已經提供了下面的示例代碼。

MSWord.Application oWordApp; 
MSWord.Document oWordDoc; 
oWordApp = new MSWord.Application(); 
oWordApp.Visible = true; 
oWordApp.WindowState = MSWord.WdWindowState.wdWindowStateMinimize; 
oWordDoc = oWordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

object start = 0; 
object end = 0; 

Microsoft.Office.Interop.Word.Range oRange = oWordDoc.Range(ref start,ref end); 

oWordDoc.InlineShapes.AddPicture(imagepath, ref oMissing, ref oMissing, oRange); 

Microsoft.Office.Interop.Word.Table tbl = oWordDoc.Tables.Add(oRange, 10, 2, ref oMissing, ref oMissing); 
Random rnd = new Random(); 
for (int i = 0; i < 10; i++) 
{ 
    tbl.Rows[i + 1].Cells[1].Range.Text = "Item#"; 
    tbl.Rows[i + 1].Cells[2].Range.Text = "Sample"; 
} 

oWordDoc.SaveAs(svd.FileName, 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); 
+2

什麼做的代碼輸出? – Raptor

+1

你期望什麼? – anothershrubery

+0

問題是什麼? – Slugart

回答

1

你試過郵件合併嗎?這樣你可以設置一個單詞模板,你可以像你想要的那樣定位你的圖像和表格。那麼你只需要擔心將輸入字段與模板合併。這樣,如果需要,您可以爲不同的文檔提供多個模板。這裏有一個例子:

Sending text to Mail-Merge Fields in Microsoft Word 2010

+0

如果你想控制格式,郵件合併是一個更好的選擇。 –

+0

而這正是我的觀點。一旦模板被設置(格式化,定位項目,設置字體等),所有需要注意的就是合併輸入。 – DarK

+0

是的,它對DarK很有幫助。謝謝。 – user1417294