回覆列表
  • 1 # hhayou

    總得可以分兩步進行,步驟一、將DocViewer控制元件新增到VS工具箱;步驟二、建立一個Windows窗體應用程式。建立程式後,可透過資料夾或者流來載入開啟Word文件。

    詳細操作如下:

    1. 初始化Form1中的元件。

    System.IO.FileStream stream;

    public Form1()

    {

    InitializeComponent();

    }

    2. 建立一個OpenFileDialog來選擇我們想要載入的正確檔案型別,否則錯誤訊息“無法檢測到當前檔案型別”將會出現。

    private void btnOpen_Click(object sender, EventArgs e)

    {

    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

    {

    this.docDocumentViewer1.LoadFromFile(dialog.FileName);

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    }

    }

    private void btnOpenStream_Click(object sender, EventArgs e)

    {

    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)

    {

    this.docDocumentViewer1.LoadFromStream(stream, Spire.Doc.FileFormat.Auto);

    }

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    }

    }

    4. 關閉開啟的檔案

    private void btnClose_Click(object sender, EventArgs e)

    {

    this.docDocumentViewer1.CloseDocument();

    }

  • 中秋節和大豐收的關聯?
  • 衛浴品牌排行榜上,有你用過的品牌嗎?