wpf .netcore 导出docx文件

发布于:2025-09-09 ⋅ 阅读:(19) ⋅ 点赞:(0)


     下载nuget包  DocX

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
   

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);
            }
        }
    }


网站公告

今日签到

点亮在社区的每一天
去签到