c#如何读取到txt中的内容并写入word中

c#完成读取txt中的文本内容,写入word中。

你参考下这里用Free Spire.Doc(从nuget搜索安装)的实现方法:

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("test.txt", Encoding.Default);

            string line;
            while ((line = sr.ReadLine()) != null)
            {
                paragraph.AppendText(line);//在段落中写入txt

                //设置段落样式,并应用到段落
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Purple;
                style1.CharacterFormat.FontName = "宋体";
                style1.CharacterFormat.FontSize = 12;
                doc.Styles.Add(style1);
                paragraph.ApplyStyle("titleStyle");
            }
            
            //保存为docx格式的Word
            doc.SaveToFile("addTxttoWord.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("addTxttoWord.docx");

        }
    }
}

效果图:

img