2012-09-11 96 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