![](/img/trans.png)
[英]Convert of word file(.docx & doc) to .pdf using c# is not working
[英]convert a word doc to text doc using C#
因此,我目前正在嘗試將單詞doc(.doc)轉換為文本文檔,因為我想在其上使用正則表達式來查找文檔中的內容。 因此,我想出了以下內容,它將Word文檔轉換為RTF格式(通過將其附加到RTF框中),但這並沒有轉換為純文本格式。 當我嘗試使用常規文本文檔時,它會在新行上打印每個單詞。 我無法在C#中找到有關如何執行此操作的任何信息。 我正在使用C#和Visual Studio 2010。
我不希望文檔中有任何特殊字符(如粗體,下划線等),但是如果有人知道我如何能夠變得更強大並提取出那些超級棒的字符。
我希望將其作為文本文檔,因為我知道我可以在常規文本上使用多種方法,但是我懷疑由於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 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.