C#在Word文档指定位置增加内容

本文介绍了如何在C#项目中利用Microsoft Word API,在已有的Word文档中,通过书签定位,实现指定位置的内容插入、删除表格及插入带边框的表格。详细步骤包括设置书签、引用Word库、操作书签范围以及处理异常。
摘要由CSDN通过智能技术生成

项目中用到再word的指定位置添加内容,所以使用了标签,以下内容转自:

http://www.cnblogs.com/Ericzhen/archive/2007/08/15/857139.html

1、在Word文档中插入一个书签,书签名称为“tl”;

2、新建一个C#项目,然后在引用中添加Word类库;由于我使用的是Office2007,因此选择的是"Microsoft Word 12.0 Object Library",如果你使用的是Office2003,就应该选择11.0;

3、在代码顶部添加对Word类库的引用;

None.gif using Word = Microsoft.Office.Interop.Word;

4、打开Word文档

None.gif object missingValue = System.Reflection.Missing.Value;
None.gif
object myTrue = false ; // 不显示Word窗口
None.gif
object fileName = @" F:\Doc1.doc " ;
None.gif Word._Application oWord
= new Word.ApplicationClass();
None.gif Word._Document oDoc;
None.gif oDoc
= oWord.Documents.Open( ref fileName, ref missingValue,
None.gif
ref myTrue, ref missingValue, ref missingValue, ref missingValue,
None.gif
ref missingValue, ref missingValue, ref missingValue,
None.gif
ref missingValue, ref missingValue, ref missingValue,
None.gif
ref missingValue, ref missingValue,
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中处理Word文档中的表格,可以使用Microsoft.Office.Interop.Word命名空间提供的API进行操作。以下是一个示例代码,可以在Word文档指定位置创建一个表格,并设置表格的行列数、表头和内容: ```csharp using System; using Microsoft.Office.Interop.Word; namespace WordTableDemo { class Program { static void Main(string[] args) { // 创建Word文档对象 Application wordApp = new Application(); Document wordDoc = wordApp.Documents.Add(); // 在指定位置插入表格 Range range = wordDoc.Range(0, 0); Table table = wordDoc.Tables.Add(range, 4, 3); // 设置表头 table.Cell(1, 1).Range.Text = "姓名"; table.Cell(1, 2).Range.Text = "年龄"; table.Cell(1, 3).Range.Text = "性别"; // 设置表格内容 table.Cell(2, 1).Range.Text = "张三"; table.Cell(2, 2).Range.Text = "18"; table.Cell(2, 3).Range.Text = "男"; table.Cell(3, 1).Range.Text = "李四"; table.Cell(3, 2).Range.Text = "20"; table.Cell(3, 3).Range.Text = "女"; table.Cell(4, 1).Range.Text = "王五"; table.Cell(4, 2).Range.Text = "22"; table.Cell(4, 3).Range.Text = "男"; // 保存Word文档 wordDoc.SaveAs2(@"D:\test.docx"); wordDoc.Close(); // 关闭Word应用程序 wordApp.Quit(); } } } ``` 在上述代码中,我们首先创建了一个Word文档对象,然后通过`Range`对象在指定位置插入了一个4行3列的表格。接着,我们通过`table.Cell(row, column)`方法获取表格中某个单元格,并设置了表头和表格内容。最后,我们将Word文档保存到本地,并关闭Word应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值