wpf .netcore 导出docx文件

下载nuget包 DocX

cs 复制代码
static int ColShowCount = 12;

  using var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    var selectedPath = folderBrowserDialog.SelectedPath;

  string FileName = Path.Combine(selectedPath, $"{Protocol.Name}.docx");

                    var fi = new FileInfo(FileName);
                    if (fi.Directory != null && !fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }
                    if (File.Exists(FileName))
                    {
                        bool has = false;
                        System.Windows.Application.Current.Dispatcher.Invoke(() =>
                        {
                            if (new IsDeleteWin("HasFile").ShowDialog() == false)
                            {
                                has = true;
                            }
                        });
                        if (has) { return; }
                    }

 // 使用 WordprocessingDocument.Create 创建 Word 文档
                using WordprocessingDocument doc = WordprocessingDocument.Create(FileName, WordprocessingDocumentType.Document);
                // 添加主文档部分
                MainDocumentPart mainPart = doc.AddMainDocumentPart();
                // 创建一个空的文档主体
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                // Add a Table into the document and sets its values.
                var prolist = new List<List<string>> { new List<string>() { "Name", xxx}, new List<string>() { "ime", xxxx} };
                DocxHelper.AddTableWithTitle(body, "", prolist);
                body.AppendChild(new Paragraph(new Run(new Text("")))); // 添加一个空行
                var doclist = new List<List<string>>();
                    doclist.Add(new List<string>() { "1111", $"{111}" });
                    doclist.Add(new List<string>() { "222", $"{222}" });
                    doclist.Add(new List<string>() { "333", $"{333}" });
                DocxHelper.AddTableWithTitle(body, "Parameter", doclist);

 var list = Global.DataHelper.QueryList();
                    if (list != null && list .Any())
                    {
                        // 添加段落分隔
                        body.AppendChild(new Paragraph(new Run(new Text(""))));
                        var conclist = new List<List<string>>();
                        foreach (var c in list )
                        {
                            conclist.Add(new List<string>() { $"{c.xxx}", $"{c.xxxx}" });
                        }
                        if (conclist?.Count > 0)
                            DocxHelper.AddTableWithTitle(body, "title.", conclist);
                    }
                mainPart.Document.Save();

}

DocxHelper.cs

cs 复制代码
internal class DocxHelper
    {
        public static void AddTableWithTitle(Body body, string title, List<List<string>> data)
        {
            try
            {
                // 添加表格标题
                var titleParagraph = new Paragraph();
                var titleRun = new Run();

                // 设置标题样式
                var titleRunProp = new RunProperties();
                titleRunProp.AppendChild(new Bold());
                titleRunProp.AppendChild(new FontSize() { Val = "24" }); // 12pt字体
                titleRun.AppendChild(titleRunProp);

                titleRun.AppendChild(new Text(title));
                titleParagraph.AppendChild(titleRun);

                // 设置段落居中
                var titleParaProp = new ParagraphProperties();
                titleParaProp.AppendChild(new Justification() { Val = JustificationValues.Left });
                titleParagraph.AppendChild(titleParaProp);
                body.AppendChild(titleParagraph);
                //body.AppendChild(new Paragraph(new Run(new Text("")))); // 添加一个空行

                // 创建表格
                Table table = CreateTable(data);
                if (table != null)
                {
                    body.AppendChild(table);
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        private static Table CreateTable(List<List<string>> data)
        {
            var table = new Table();
            try
            {
                // 设置表格属性
                var tblProp = new TableProperties(
                    new TableWidth() { Width = "9000", Type = TableWidthUnitValues.Dxa },
                    new TableJustification() { Val = TableRowAlignmentValues.Left }
                );

                // 设置表格边框为实线
                var tblBorders = new TableBorders(
                    new TopBorder()
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12,
                        Color = "000000"
                    },
                    new BottomBorder()
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12,
                        Color = "000000"
                    },
                    new LeftBorder()
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12,
                        Color = "000000"
                    },
                    new RightBorder()
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12,
                        Color = "000000"
                    },
                    new InsideHorizontalBorder()
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12,
                        Color = "000000"
                    },
                    new InsideVerticalBorder()
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12,
                        Color = "000000"
                    }
                );

                tblProp.AppendChild(tblBorders);
                table.AppendChild(tblProp);

                // 创建表格行
                for (int i = 0; i < data.Count; i++)
                {
                    var tr = new TableRow();

                    for (int j = 0; j < data[i].Count; j++)
                    {
                        var tc = new TableCell();
                        // 设置单元格属性
                        var tcProp = new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa }
                        );

                        // 如果是表头行,设置背景色
                        //if (i == 0)
                        //{
                        //    tcProp.AppendChild(new Shading()
                        //    {
                        //        Val = ShadingPatternValues.Clear,
                        //        Color = "auto",
                        //        Fill = "D9D9D9"
                        //    });
                        //}

                        tc.AppendChild(tcProp);

                        // 创建段落和文本
                        var para = new Paragraph();
                        var run = new Run();

                        // 如果是表头,设置粗体
                        //if (i == 0)
                        //{
                        //    var runProp = new RunProperties();
                        //    runProp.AppendChild(new Bold());
                        //    run.AppendChild(runProp);
                        //}

                        run.AppendChild(new Text(data[i][j]));
                        para.AppendChild(run);
                        tc.AppendChild(para);
                        tr.AppendChild(tc);
                    }

                    table.AppendChild(tr);
                }
            }
            catch (System.Exception)
            {
                return null;
                throw;
            }
            return table;
        }

        public static void CreateTitile(Body body, string title)
        {
            try
            {
                // 添加表格标题
                var titleParagraph = new Paragraph();
                var titleRun = new Run();

                // 设置标题样式
                var titleRunProp = new RunProperties();
                titleRunProp.AppendChild(new Bold());
                titleRunProp.AppendChild(new FontSize() { Val = "24" }); // 12pt字体
                titleRun.AppendChild(titleRunProp);

                titleRun.AppendChild(new Text(title));
                titleParagraph.AppendChild(titleRun);

                // 设置段落居中
                var titleParaProp = new ParagraphProperties();
                titleParaProp.AppendChild(new Justification() { Val = JustificationValues.Left });
                titleParagraph.AppendChild(titleParaProp);
                body.AppendChild(titleParagraph);
            }
            catch (System.Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
        }
    }
相关推荐
donk13141 小时前
React Native for OpenHarmony 实战:三方库 react-native-step-indicator 的鸿蒙化适配指南
分布式·react native·react.js·wpf·harmonyos
He BianGu3 小时前
【笔记】WPF中RenderOptions类的详细功能
笔记·wpf
VidDown6 小时前
上线三个月后的第一次事故:一个 Django 服务的日志、监控与故障复盘
数据库·python·django·wpf·音视频·视频编解码
He BianGu6 小时前
【笔记】WPF中CachingHint的功能
笔记·wpf
He BianGu8 小时前
【笔记】在WPF中BitmapScalingMode的作用
笔记·wpf
Vae_Mars1 天前
幂等性学习笔记
笔记·学习·wpf
宝桥南山1 天前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore
samble2 天前
从零搭建灌装监控系统(十九):单元测试实战,xUnit + 内存SQLite + 反射测试私有方法
c#·wpf·mvvm·modbus·工业控制
光泽雨3 天前
路由概念和路由事件 继承链路 RadioButton的事件解析
wpf
samble3 天前
从零搭建灌装监控系统(十八):自定义控件,三色灯与状态指示
c#·wpf·mvvm·modbus·工业控制