解析Word 2007 文件 - 取得文字內容

解析Word 2007 文件 - 取得文字內容

加入WindowsBase.dll 到參考

using System.IO;
using System.IO.Compression;
using System.IO.Packaging;
using System.Xml;
...
private void button1_Click(object sender, EventArgs e)
{            
    OpenFileDialog op = new OpenFileDialog();
    op.DefaultExt = "docx";
    op.Filter = "Word 2007 文件|*.docx";
    op.Title = "開啟Word 2007 文件";
    if (op.ShowDialog() == DialogResult.OK)
    {                                
        using (Package package = Package.Open(op.FileName , FileMode.Open, FileAccess.Read))
        {                    
                Uri docxUri = new Uri("/word/document.xml", UriKind.Relative);
                PackagePart docxPart = package.GetPart(docxUri);
                XmlDocument docxXmlDocument = new XmlDocument();                    
                docxXmlDocument.Load(docxPart.GetStream());
                MessageBox.Show(docxXmlDocument.InnerText, "message");
                package.Close();
        }
    }
}