C#を使用してtxtファイルを読み取ってWord文書を生成する方法


この記事では、C#プログラムコードを例として取り上げ、txtファイルのコンテンツを読み取ってWord文書を生成する方法を紹介します。コードを編集する前に、次のコード環境を参照して構成を確認できます。

Visual Studio 2017
.Net Framework 4.6.1
Free Spire.Doc for .NET
.txtドキュメント

dllファイルのインストールする3つの方法

1. NuGetを介してdllをインストールする方法

1.1 Visual Studioで「ソリューションエクスプローラー」を開き、「参照」、「NuGetパッケージの管理」を右クリックし、「無料のSpire.Doc」を検索して、「インストール」をクリックします。プログラムのインストールが完了するのを待ちます。

1.2以下をPMコンソールのインストールにコピーします。
Install-Package FreeSpire.Doc -Version 9.9.7

2. dll参照を手動で追加する

パッケージを手動でダウンロードして解凍し、BINフォルダーでSpire.Doc.dllを見つけることができます。次に、Visual Studioで「ソリューションエクスプローラー」を開き、「参照」、「参照の追加」を右クリックして、プログラムへのローカルパスのBINフォルダーにあるdllファイルへの参照を追加します。

txtを読み取りWordを生成する

StreamReader(Stream stream、Encoding encoding)構築メソッドを使用して、指定されたパスにあるtxtファイルを読み取ります。
Free Spire.Docが提供するParagraph.AppendText(string text)メソッドを使用して、読み取り済みのtxtコンテンツをWord段落に追加します。
最後に、Document.SaveToFile(string fileName、FileFormat fileFormat)メソッドを使用してWordとして保存し、保存パスを指定します。

コード一覧

C#

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

namespace CreateWordDocument_Doc
{
    class Program
    {
        static void Main(string[] args)
        {
            //Documentクラスのオブジェクトをインスタンス化し、sectionとparagraphを追加する
            Document doc = new Document();
            Section section = doc.AddSection();
            Paragraph paragraph = section.AddParagraph();

            //txtファイルを読み取る
            StreamReader sr = new StreamReader("C:\\Users\\Administrator\\Desktop\\test.txt", Encoding.Default);

            //段落スタイルを設定し、段落に適用する
            ParagraphStyle style1 = new ParagraphStyle(doc);
            style1.Name = "titleStyle";
            style1.CharacterFormat.Bold = true;
            style1.CharacterFormat.TextColor = Color.Purple;
            style1.CharacterFormat.FontName = "Yu Mincho";
            style1.CharacterFormat.FontSize = 12;
            doc.Styles.Add(style1);
            paragraph.ApplyStyle("titleStyle");

            string line;
            while ((line = sr.ReadLine()) != null)
            {
                paragraph.AppendText(line);//段落にtxtを書く                
            }
            //docx形式でWordとして保存する
            doc.SaveToFile("addTxttoWord.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("addTxttoWord.docx");
        }
    }
}

VB.NET

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

Namespace CreateWordDocument_Doc
    Class Program
        Shared  Sub Main(ByVal args() As String)
            'Documentクラスのオブジェクトをインスタンス化し、sectionとparagraphを追加する
            Document doc  =  New Document()
            Dim section As Section =  doc.AddSection() 
            Dim paragraph As Paragraph =  section.AddParagraph() 

            'txtファイルを読み取る
            Dim sr As StreamReader =  
New StreamReader("C:\\Users\\Administrator\\Desktop\\test.txt",Encoding.Default) 

            '段落スタイルを設定し、段落に適用する
            Dim style1 As ParagraphStyle =  New ParagraphStyle(doc) 
            style1.Name = "titleStyle"
            style1.CharacterFormat.Bold = True
            style1.CharacterFormat.TextColor = Color.Purple
            style1.CharacterFormat.FontName = "Yu Mincho"
            style1.CharacterFormat.FontSize = 12
            doc.Styles.Add(style1)
            paragraph.ApplyStyle("titleStyle")

            Dim line As String
            While Not(line = sr.ReadLine()) Is Nothing
                paragraph.AppendText(line)'段落にtxtを書く                
            End While
            'docx形式でWordとして保存する
            doc.SaveToFile("addTxttoWord.docx", FileFormat.Docx2013)
            System.Diagnostics.Process.Start("addTxttoWord.docx")

        End Sub
    End Class
End Namespace

生成したドキュメントの効果は以下のようになります:

結語

以上は今回のTXTを読み取ってWord文書を生成する記事でした、最後まで読んでいただきありがとうございます。