【问题标题】:Create word documents in C#在 C# 中创建 Word 文档
【发布时间】:2012-09-11 09:50:44
【问题描述】:

我正在尝试使用 Microsoft Office 互操作创建 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);

【问题讨论】:

  • 图像被添加到表格的第一个单元格中。

标签: c# .net interopservices


【解决方案1】:

您尝试过邮件合并吗?这样您就可以设置单词模板,并且可以随意放置图像和表格。然后您只需要担心将输入字段与模板合并。这样,如果需要,您可以为不同的 Word 文档创建多个模板。这是一个例子:

Sending text to Mail-Merge Fields in Microsoft Word 2010

【讨论】:

  • 如果您想控制格式,邮件合并是一个更好的选择。
  • 这也是我的观点。一旦模板设置好(格式化、定位项目、设置字体等),所有需要注意的就是与输入的合并。
  • 是的,Dark 很有帮助。谢谢。
  • @user1417294:很高兴它有帮助。如果它解决了您的问题,请不要忘记将此标记为您的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 2011-07-29
  • 2012-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多