开头调用C#的Word连接库:
using Word=Microsoft.Office.Interop.Word;
建立一个Word对象以及一些创建对象时会用到的变量,oWord是word应用程序,oDoc是里面的文档
public Word._Application oWord= new Word.Application();
public object oFileName = @"C:\XXX.docx";
public object oReadOnly = true;
public object oMissing = System.Reflection.Missing.Value;
public object dontsave = Word.WdSaveOptions.wdDoNotSaveChanges;
public object save = Word.WdSaveOptions.wdPromptToSaveChanges;
Word._Document oDoc
打开word文档
//打开word文档
oDoc = oWord.Documents.Open(ref path, ref oMissing, ref oReadOnly, 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);
然后是进行操作,比如读表
//读取第一个映射表
Word.Table currTab = oDoc.Tables[1];
for (int row = 1; row < currTab.Rows.Count; row++)
{
string text = currTab.Cell(row + 1, 1).Range.Text;
}
不过别忘了word文档读取出来的字符都带有回车符,不删除的话会显示成乱码
//去除word文档中自带的回车符
private string del_enter(string s)
{
return s.Remove(s.Length - 2, 2);
}
最后别忘了保存文档,关闭word应用程序
oDoc.Close(ref dontsave, ref oMissing, ref oMissing);
oWord.Quit(ref dontsave, ref oMissing, ref oMissing);