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);
            }
        }
    }
相关推荐
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
柒.梧.5 天前
基于SpringBoot+JWT 实现Token登录认证与登录人信息查询
wpf
小先生8126 天前
.NET Core后台任务队列
.net·.netcore
MoFe16 天前
【.net core】【watercloud】动态数据转换为静态表格,或者表格数据返回需要后处理
.netcore
十月南城8 天前
Flink实时计算心智模型——流、窗口、水位线、状态与Checkpoint的协作
大数据·flink·wpf
听麟11 天前
HarmonyOS 6.0+ 跨端会议助手APP开发实战:多设备接续与智能纪要全流程落地
分布式·深度学习·华为·区块链·wpf·harmonyos
@hdd11 天前
Kubernetes 可观测性:Prometheus 监控、日志采集与告警
云原生·kubernetes·wpf·prometheus
zls36536511 天前
C# WPF canvas中绘制缺陷分布map
开发语言·c#·wpf
专注VB编程开发20年11 天前
c#Redis扣款锁的设计,多用户,多台电脑操作
wpf
吹牛不交税12 天前
.netcore项目部署在ubuntu22.04虚拟机的docker中的过程记录
docker·容器·.netcore