gpt4 book ai didi

c# - 使用 C# 将 word 文档转换为文本文档

转载 作者:行者123 更新时间:2023-11-30 22:06:21 24 4
gpt4 key购买 nike

所以我目前正在尝试将 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
}


}
}

最佳答案

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
}

关于c# - 使用 C# 将 word 文档转换为文本文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23687066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com