如何使用Spire.DocViewer打开和浏览Word文件

作者:控件中国网   出处:控件中国网   2015-08-04 14:27:52   阅读:39

Spire.DocViewer是一款Word浏览以及处理控件,使用该控件可以轻松浏览多个版本的Word文件,并可以对打开的Word文件进行格式转换,下面就简单介绍如何在WinForm 应用程序中快速创建Word浏览程序,具体如下:

1.下载并安装Spire.DocViewer,并且添加DocViewer控件到Visual Studio的工具箱里

Open_Close_Word_1.png
2.创建一个Windows Forms应用程序,并添加以下按钮到窗体上 'Open from file'和'Open from stream' 以及 'Close' 按钮,并拖拉DocDocumentViewer控件到窗体上

Open_Close_Word_2.png
3.在btnOpen_Click事件里添加下面的代码
private void btnOpen_Click(object sender, EventArgs e)
        {
            //open a DOC document
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Word97-2003 files(*.doc)|*.doc|Word2007-2010 files (*.docx)|*.docx|All files (*.*)|*.*";
            dialog.Title = "Select a DOC file";
            dialog.Multiselect = false;
            dialog.InitialDirectory = System.IO.Path.GetFullPath(@"..\..\..\..\..\..\Data");

            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                try
                {
                    //Load DOC document from file.
                    this.docDocumentViewer1.LoadFromFile(dialog.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
4.在btnOpenStream_Click事件里添加如下代码,该按钮主要是用于客户以流的形式打开Word
private void btnOpenStream_Click(object sender, EventArgs e)
{
    //open a doc document
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.Filter = "Word97-2003 files(*.doc)|*.doc|Word2007-2010 files (*.docx)|*.docx|All files (*.*)|*.*";
    dialog.Title = "Select a DOC file";
    dialog.Multiselect = false;
    dialog.InitialDirectory = System.IO.Path.GetFullPath(@"..\..\..\..\..\..\Data");
   
    DialogResult result = dialog.ShowDialog();

    if (result == DialogResult.OK)
    {
        try
        {
            string docFile = dialog.FileName;
            stream = new System.IO.FileStream(docFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            if (stream != null)
            {
                //Load doc document from stream.
                this.docDocumentViewer1.LoadFromStream(stream, Spire.Doc.FileFormat.Auto);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
5.在btnClose_Click按钮里添加如下代码
private void btnClose_Click(object sender, EventArgs e)
{
    //Close current doc document.
    this.docDocumentViewer1.CloseDocument();
}
6.运行程序可以看到下面的效果
Open_Close_Word_3.png

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat