要在WinForm應用程序中讀取并顯示Word文檔,您可以使用Microsoft Office Interop庫。下面是一個示例代碼,演示了如何讀取Word文檔并將其內容顯示在WinForm的TextBox控件中:
using Microsoft.Office.Interop.Word;
using System;
using System.Windows.Forms;
namespace ReadWordDocument
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Word Documents|*.doc;*.docx";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
object missing = System.Reflection.Missing.Value;
object filePath = openFileDialog.FileName;
Document doc = wordApp.Documents.Open(ref filePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
string content = "";
foreach (Paragraph paragraph in doc.Paragraphs)
{
content += paragraph.Range.Text;
}
txtContent.Text = content;
doc.Close();
wordApp.Quit();
}
}
}
}
在上面的代碼示例中,首先通過OpenFileDialog控件讓用戶選擇要打開的Word文檔。然后使用Microsoft Office Interop庫中的Application和Document類打開文檔,并遍歷文檔的每個段落,將內容讀取并顯示在TextBox控件中。
請注意,使用Microsoft Office Interop庫需要安裝相應的Office軟件,并且在項目中添加對應的COM引用。另外,由于Interop庫可能會導致一些性能問題和兼容性問題,因此建議在生產環境中使用更穩定的方式來處理Word文檔,比如使用Open XML SDK或第三方庫。