今天头次接触使用程序操作Word,特此记录下。
首先,添加引用 Microsoft.Office.Interop.Word
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReadWord
{
class OpenWord
{
public Microsoft.Office.Interop.Word.Application app { get; set; }
public Microsoft.Office.Interop.Word.Document doc { get; set; }
object _null = System.Reflection.Missing.Value;
public void Open(string filePath)
{
app = new Microsoft.Office.Interop.Word.Application();
object file = filePath;
if (doc == null)
{
//_doc = new Microsoft.Office.Interop.Word.Document();
}
doc = app.Documents.Open(
ref file, ref _null, ref _null,
ref _null, ref _null, ref _null,
ref _null, ref _null, ref _null,
ref _null, ref _null, ref _null,
ref _null, ref _null, ref _null, ref _null);
}
}
}
再写一个测试程序,调用Open函数
程序输出的就是这部分,不过这里是按什么区分tables中的顺序的,这块有些不明白了,难道不是按照word中的顺序吗?从结果上看好像就是这样。
我遇到的问题是需要在模板word中,按照模板的表格模式,往下追加程序的数据。对于一个六列的表格。
Microsoft.Office.Interop.Word.Table table = document.Tables[1];
table.Rows.Add();
table.Cell(table.Rows.Count, 1).Range.Text = "1";
table.Cell(table.Rows.Count, 2).Range.Text = "2";
table.Cell(table.Rows.Count, 3).Range.Text = "3";
table.Cell(table.Rows.Count, 4).Range.Text = "4";
table.Cell(table.Rows.Count, 5).Range.Text = "5";
table.Cell(table.Rows.Count, 6).Range.Text = "6";
WORD中表格依次就会出现添加的信息。