C#通过DocX创建word

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

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

2.示例代码

复制代码
class Program
{
    static void Main(string[] args)
    {
        string path = @"C:\Users\Administrator\Desktop\test.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.最终效果图

 

posted @   段江涛IT  阅读(2740)  评论(11编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2017-04-26 C# int.ToString() 常用参数说明
2016-04-26 C#异常信息获取
页脚HTML代码
点击右上角即可分享
微信分享提示