基本信息
源码名称:c# Winform 根据word模板生成word
源码大小:21.19M
文件格式:.rar
开发语言:C#
更新时间:2024-05-15
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

简介:DocX插件读取word模板,需要替换的地方用$$标识。


string filepath = Application.StartupPath "\\ReportDefault.docx";


            // 假设你要插入的表格数据  
            var tableData = new List<List<string>>
            {
                new List<string> { "Header 1", "Header 2" },
                new List<string> { "Data 1", "Data 2" },
                new List<string> { "Data 3", "Data 4" }
            };


            using (var document = DocX.Load(filepath))
            {
                // 假设模板中有一个段落包含文本 "PLACEHOLDER"  
                // 遍历段落并替换文本  
                foreach (Paragraph paragraph in document.Paragraphs)
                {
                    if (paragraph.Text.Contains("$name$"))
                    {
                        // 使用 ReplaceText 方法替换段落中的文本(注意:这个方法可能因库版本而异)  
                        // 如果库没有这个方法,你可能需要手动构建新的段落并替换旧的段落  
                        paragraph.ReplaceText("$name$", "这是渲染后的内容", false, System.Text.RegularExpressions.RegexOptions.None);
                    }//$caseid$
                }

                // 查找包含 "$table$" 的段落  
                var placeholderParagraph = document.Paragraphs.FirstOrDefault(p => p.Text.Contains("$tables$"));

                if (placeholderParagraph != null)
                {
                    // 在找到的位置插入新的表格  
                    Table table = placeholderParagraph.InsertTableBeforeSelf(tableData.Count, tableData[0].Count);
                   
                    for (int rowIndex = 0; rowIndex < tableData.Count; rowIndex )
                    {
                        for (int cellIndex = 0; cellIndex < tableData[rowIndex].Count; cellIndex )
                        {
                            table.Rows[rowIndex].Cells[cellIndex].Paragraphs.First().Append(tableData[rowIndex][cellIndex]);
                        }
                    }
                    placeholderParagraph.Remove(false);
                }
                else
                {
                    // 如果没有找到 "$table$" 标记,则输出错误消息或进行其他处理  
                    Console.WriteLine("The placeholder '$table$' was not found in the document.");
                }

                
                // 保存修改后的 Word 文档  
                document.SaveAs("output.docx");
            }