当前位置:网站首页>C#/VB.NET Word转Text

C#/VB.NET Word转Text

2022-06-23 21:49:00 51CTO

相信大家经常会在Word文档中编写文章,但是有时候我们需要将Word文档转换成txt格式。而txt格式相较于其他格式来说,

  • 体积小、存储简单方便
  • txt格式比较简单,不会中毒
  • txt格式是电脑和很多移动设备的通用格式

今天这篇文章将以C#/VB.NET代码为例,向大家详细介绍如何将Word转成txt格式。详情请阅读以下内容。

程序环境:

本次测试时,在程序中引入Free Spire.Doc for .NET。可通过以下方法引用Spire.Doc.dll文件:

方法1:将 ​ ​Free Spire.Doc for .NET​​ 下载到本地,解压,安装。安装完成后,找到安装路径下BIN文件夹中的Spire.Doc.dll。然后在Visual Studio中打开“解决方案资源管理器”,鼠标右键点击“引用”,“添加引用”,将本地路径BIN文件夹下的dll文件添加引用至程序。

方法2:通过 ​ ​NuGet​​ 安装。可通过以下2种方法安装:

(1)可以在Visual Studio中打开“解决方案资源管理器”,鼠标右键点击“引用”,“管理NuGet包”,然后搜索“Free Spire.Doc”,点击“安装”。等待程序安装完成。

(2)将以下内容复制到PM控制台安装。

Install-Package FreeSpire.Doc -Version 10.2.0

将Word转为Text

  • ​创建一个Document实例。
  • 使用 Document.LoadFromFile() 方法加载 Word 示例文档。
  • 使用 Document.SaveToFile() 方法将文档保存为 TXT 文件。​

[C#]

      
      
using System. Data;
using System. Drawing;
using System. Text;
using Spire. Doc;
using Spire. Doc. Documents;

namespace ConsoleApplication2


{
class Program
{
static void Main( string[] args)
{
//新建一个文档.
Document document = new Document();

//加载实例文档.
document. LoadFromFile( "NewSample1.docx");

string result = "Result-WordToText.txt";

//保存文档.
document. SaveToFile( result, FileFormat. Txt);
}
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

【VB.NET】

      
      
Imports System .Data
Imports System .Drawing
Imports System .Text
Imports Spire .Doc
Imports Spire .Doc .Documents

Namespace ConsoleApplication2

Class Program

Private Shared Sub Main( ByVal args() As String)
'新建一个文档.
Dim document As Document = New Document
'加载实例文档.
document .LoadFromFile( "NewSample1.docx")
Dim result As String = "Result-WordToText.txt"
'保存文档.
document .SaveToFile( result, FileFormat .Txt)
End Sub
End Class
End Namespace
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

效果图:

C#/VB.NET Word转Text_Word

注意:代码中生成的文档路径为的VS程序的Debug路径,文件路径也可自定义为其他路径。

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://blog.51cto.com/u_15656056/5412229