我正在尝试将一个word文档(.doc)转换为文本文档,以便能够使用正则表达式在文档中查找内容。我编写了以下代码,将word文档转换为富文本格式(通过将其添加到富文本框),但这并没有转化为纯文本格式。当我用普通文本文档尝试时,它会将每个单词打印在新行上。我没有找到任何关于如何在C#中实现这一点的信息。我正在使用C#和Visual Studio 2010。
我不希望在文档中出现特殊字符(如粗体、下划线等),但如果有人知道如何提取这些字符并使其更加健壮,那就太棒了。
我需要将其作为文本文档,因为我知道几种适用于常规文本的方法,但我怀疑它们对于带有word文档中隐藏/特殊字符的文本可能无法正常工作。
我不希望在文档中出现特殊字符(如粗体、下划线等),但如果有人知道如何提取这些字符并使其更加健壮,那就太棒了。
我需要将其作为文本文档,因为我知道几种适用于常规文本的方法,但我怀疑它们对于带有word文档中隐藏/特殊字符的文本可能无法正常工作。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
namespace ReadWordDocProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string testFile = @"C:\Users\<mycomputer>\Documents\TestItemHelpers\TestWordDoc.docx";
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Document document = application.Documents.Open(testFile);//path here
int count = document.Words.Count;
for (int i = 1; i <= count; i++)
{
string text = document.Words[i].Text;
//Do output with text here
richTextBox1.AppendText(text);
}
((_Application)application).Quit(); //cast as _Application because there's ambiguity
}
}
}