在文本框中显示Word文件的内容

时间:2017-11-23 12:09:57

标签: c# .net ms-word textbox

我有一个启用了muiltilne选项的文本框。 我想将特定word文件的内容显示到该文本框中。我怎样才能做到这一点?我使用这段代码,但它只是显示文件的名称。

private void btnOpen_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Title = "Open Word File";
    openFileDialog1.Filter = "Word Files (*doc)|*docx";   

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();

        object fileName = openFileDialog1.FileName;
        // Define an object to pass to the API for missing parameters
        object missing = System.Type.Missing;
        doc = word.Documents.Open(ref fileName,ref missing, ref missing);

        String read = string.Empty;
        List<string> data = new List<string>();
        for (int i = 0; i < doc.Paragraphs.Count; i++)
        {
            string temp = doc.Paragraphs[i + 1].Range.Text.Trim();
            if (temp != string.Empty)
            data.Add(temp);
        }
        doc.Close();
        word.Quit();   
        txtTxt.Text = data.ToString();

    } 
}

这是C#中的Windows窗体应用程序。

请帮忙!

2 个答案:

答案 0 :(得分:0)

您正在使用

行将数据添加到文本框中
txtTxt.Text = data.ToString();

data是一个字符串列表。除非你重载了.ToString()方法,否则这样分配它将不起作用。

遍历列表并将其添加到文本框中。像这样的东西

foreach(var item in data)
{
    txtTxt.Text += item;
}

答案 1 :(得分:0)

找到解决方案。 只需要在最后添加一个循环。感谢“Mohamed Najiullah”。

private void btnOpen_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Title = "Open Word File";
    openFileDialog1.Filter = "Word Files (*doc)|*docx";   

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();

        object fileName = openFileDialog1.FileName;
        // Define an object to pass to the API for missing parameters
        object missing = System.Type.Missing;
        doc = word.Documents.Open(ref fileName,ref missing, ref missing);

        String read = string.Empty;
        List<string> data = new List<string>();
        for (int i = 0; i < doc.Paragraphs.Count; i++)
        {
            string temp = doc.Paragraphs[i + 1].Range.Text.Trim();
            if (temp != string.Empty)
            data.Add(temp);
        }
        doc.Close();
        word.Quit();   
       foreach(var item in data)
{
    txtTxt.Text += item;
}

    } 
}