使用C#将单词doc转换为文本doc

问题描述 投票:2回答:1

所以我目前正在尝试将单词doc(.doc)转换为文本文档,因为我想在其上使用正则表达式来查找文档中的内容。所以我提出了下面的内容,它将word文档转换为富文本格式(通过将其附加到富文本框),但这并不能转换为纯文本格式。当我尝试使用常规文本文档时,它会在新行上打印每个单词。我无法在C#中找到有关如何执行此操作的任何信息。我正在使用C#和visual studio 2010。

我不希望文档中有任何特殊字符(如粗体,下划线等),但如果有人知道我如何能够健壮并提取那些非常棒的文章。

我希望它作为一个文本文档,因为我知道我可以在常规文本上使用几种方法,但我怀疑它们是否可以处理文字文本,因为隐藏/特殊字符带有文字文档。

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 
        }


    }
}
c# regex text ms-word converter
1个回答
3
投票

Microsoft说你不应该使用Microsoft Office Interop来操作自动化应用程序中的文档。

您可以使用像Spire Doc这样的免费库将Word Doc转换为TXT,然后打开txt文件。我认为有一种方法可以直接从Spire直接存入MemoryStream,但我不确定。 (我知道有Aspose Words,但这不是免费的)。

private void button1_Click(object sender, EventArgs e)
{
    //Open word document
    Document document = new Document();
    string docPath = @"C:\Users\<computer name>\Documents\TestItemHelpers";

    document.LoadFromFile(Path.Combine(docPath,"TestWordDoc.docx"));

    //Save doc file.
    document.SaveToFile(Path.Combine(docPath,"TestTxt.txt"), FileFormat.Txt);

    string readText = File.ReadAllText(Path.Combine(docPath,"TestTxt.txt"));

    //do regex here
}

编辑:如果您要使用Interop,因为它可以用于用户运行的活动(如注释中所指出的),您可以将文档保存为文本文件,然后执行正则表达式:

private void button1_Click(object sender, EventArgs e)
{
    string docPath = @"C:\Users\<computer name>\Documents\TestItemHelpers"
    string testFile = "TestWordDoc.docx";

    Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
    Document document = application.Documents.Open(Path.Combine(docPath,testFile );
    application.ActiveDocument.SaveAs(Path.Combine(docPath,"TestTxt.txt"), WdSaveFormat.wdFormatText, ref noEncodingDialog);
    ((_Application)application).Quit();

    string readText = File.ReadAllText(Path.Combine(docPath,"TestTxt.txt"));

    //do regex here
}
© www.soinside.com 2019 - 2024. All rights reserved.