在C#中排序Microsoft.Office.Interop.Word

时间:2014-02-05 03:25:57

标签: c# sorting ms-word document

我使用Microsoft.Office.Interop.Word从Word文件中获取单词,然后将其填充到表格布局面板中。不幸的是,表格布局面板上显示的单词不遵循Word文件中的确切顺序。

如何解决这个问题?

// Open a doc file.
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Document d ocument = application.Documents.Open(txtUploadedPathToken.Text);

// Loop through all words in the document.
int count = document.Words.Count;

for (int i = 1; i <= count; i++)
{
    // Write the word.
    string text = document.Words[i].Text;
    //Console.WriteLine("Word {0} = {1}", i, text);
    tableLayoutPanel2.Controls.Add(new Label() { Text = text, Anchor = AnchorStyles.Left, AutoSize = true}, 0, 0);
}

1 个答案:

答案 0 :(得分:0)

您的word文档阅读代码似乎没问题。但您可能需要更改向面板添加项目的方式。由于您将新项目添加到同一位置(0,0),因此可能会给出错误的订单。

foreach (Microsoft.Office.Interop.Word.Range range in document.Words)
{
   string text = range.Text;
   tableLayoutPanel2.Controls.Add(new Label() { Text = text, Anchor = AnchorStyles.Left, AutoSize = true});
}