您的位置:首页 > 编程语言 > C#

C# 简单操作word(可使用模版)

2017-06-19 20:49 357 查看
1.右键引用–>添加引用–>程序集:

Microsoft.Office.Interp.Word

2.在文档中添加using:

Using MsWord = Microsoft.Office.Interp.Word;

3.把引用中的Microsoft.Office.Interop.Word的“属性”中的嵌入互操作设为False

4.创建word应用程序

MsWord.Application wordApp = new MsWord.ApplicationClass();

5.使其可见:

wordApp.Visible = true;

6.使用word模版,打开Word编写模版,另存为在项目bin\Debug下

MsWord.Document md = wordApp.Documents.Add(Environment.CurrentDirectory + "\\Module.doc");


7.打开模版文档,可编辑状态

MsWord.Document wordDoc = wordApp.Documents.Open(Environment.CurrentDirectory + "\\Module.doc");


8.将模版中已创建的表保存为table:

MsWord.Table table = wordDoc.Tables[1];

9.插入图片:

需要图片路径地址 ImgUrl

//定义该插入图片是否为外部链接
object linkToFile = true;

//定义插入图片是否随word文档一起保存
object saveWithDocument = true;

table.Rows[1].Cells[2].Select(); //光标选择在需要插入图片的位置
object range = wordApp.Selection.Range;

//插入图片
MsWord.InlineShape shape = wordApp.ActiveDocument.InlineShapes.AddPicture(ImgUrl, ref linkToFile, ref saveWithDocument, ref range);
//定义宽高
shape.Width = 60;
shape.Height = 70;


10.Range.Text 插入文本

for (int i = 1; i < 31; i++) //插入其余信息
{
try
{
table.Rows[i+1].Cells[2].Range.Text = dataGridView1.CurrentRow.Cells[i-1].Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐