Spire.DocViewer是一款Word浏览以及处理控件,使用该控件可以轻松浏览多个版本的Word文件,并可以对打开的Word文件进行格式转换,下面就简单介绍如何在WinForm 应用程序中快速创建Word浏览程序,具体如下:
1.下载并安装Spire.DocViewer,并且添加DocViewer控件到Visual Studio的工具箱里
2.创建一个Windows Forms应用程序,并添加以下按钮到窗体上 'Open from file'和'Open from stream' 以及 'Close' 按钮,并拖拉DocDocumentViewer控件到窗体上
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.运行程序可以看到下面的效果