【发布时间】:2014-05-15 19:30:19
【问题描述】:
所以我目前正在尝试将 word doc (.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
}
}
}
【问题讨论】:
-
“当我尝试使用常规文本文档时,它会在新行中打印每个单词”您在这里尝试的代码是什么?
-
作为非编程解决方案,您是否尝试过从 Word 中复制整个文档内容并将其粘贴到文本编辑器中?如果这只是一次性任务,那肯定是获取纯文本文档的最快途径。
-
我会收到很多这样的文件,手动操作似乎有点不切实际。我知道如何手工完成,但我希望有一个更简单的解决方案。
-
@BenAaronson 我逐行写入文本文档只是为了测试它是否有效。您是否认为 word doc 中的某些特殊字符可以将文本等效行翻译为 word doc 的单个单词?...
标签: c# regex text ms-word converter