C#通过DocX创建word

网上有一些基础的东西,但是比如插入图片,就没有找到方案,最终自己摸索出来的。

1.首先通过Nuget获取引用,关键字:“DocX”

2.示例代码

class Program
{
    static void Main(string[] args)
    {
        string path = @"C:UsersAdministratorDesktop	est.docx";
        using (var document = DocX.Create(path))
        {
            //文字居中对齐
            document.InsertParagraph().Append("自定义word").Alignment = Alignment.center;
            //文字加粗
            document.InsertParagraph().Append("我要加粗").Bold();
            //插入表格
            Table table=document.AddTable(2,3);
            table.Rows[0].Cells[0].Paragraphs[0].Append("第一行第一列");
            table.Rows[0].Cells[1].Paragraphs[0].Append("第一行第二列");                        
            table.InsertRow();
            document.InsertTable(table);

            //插入图片
            Image image = document.AddImage("d:\title.jpg");
            Picture picture= image.CreatePicture();
            document.InsertParagraph().AppendPicture(picture);
            document.Save();
        }
        Console.WriteLine(path);
    }
}

 3.最终效果图

原文地址:https://www.cnblogs.com/duanjt/p/10774266.html